e0479f615a7c449d027c4b4dffafb7e7a9e5c92a
[dragonfly.git] / sys / netinet6 / esp_input.c
1 /*      $FreeBSD: src/sys/netinet6/esp_input.c,v 1.1.2.8 2003/01/23 21:06:47 sam Exp $  */
2 /*      $DragonFly: src/sys/netinet6/esp_input.c,v 1.3 2003/07/23 02:30:22 dillon Exp $ */
3 /*      $KAME: esp_input.c,v 1.62 2002/01/07 11:39:57 kjc Exp $ */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * RFC1827/2406 Encapsulated Security Payload.
36  */
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/mbuf.h>
44 #include <sys/domain.h>
45 #include <sys/protosw.h>
46 #include <sys/socket.h>
47 #include <sys/errno.h>
48 #include <sys/time.h>
49 #include <sys/syslog.h>
50
51 #include <net/if.h>
52 #include <net/route.h>
53 #include <net/netisr.h>
54 #include <machine/cpu.h>
55
56 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/ip.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/in_var.h>
61 #include <netinet/ip_ecn.h>
62 #ifdef INET6
63 #include <netinet6/ip6_ecn.h>
64 #endif
65
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet6/in6_pcb.h>
69 #include <netinet6/ip6_var.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/ip6protosw.h>
72 #endif
73
74 #include <netinet6/ipsec.h>
75 #ifdef INET6
76 #include <netinet6/ipsec6.h>
77 #endif
78 #include <netinet6/ah.h>
79 #ifdef INET6
80 #include <netinet6/ah6.h>
81 #endif
82 #include <netinet6/esp.h>
83 #ifdef INET6
84 #include <netinet6/esp6.h>
85 #endif
86 #include <netkey/key.h>
87 #include <netkey/keydb.h>
88 #include <netkey/key_debug.h>
89
90 #include <machine/stdarg.h>
91
92 #include <net/net_osdep.h>
93
94 #define IPLEN_FLIPPED
95
96 #define ESPMAXLEN \
97         (sizeof(struct esp) < sizeof(struct newesp) \
98                 ? sizeof(struct newesp) : sizeof(struct esp))
99
100 #ifdef INET
101 #include <netinet/ipprotosw.h>
102 extern struct ipprotosw inetsw[];
103
104 void
105 esp4_input(struct mbuf *m, int off, int proto)
106 {
107         struct ip *ip;
108         struct esp *esp;
109         struct esptail esptail;
110         u_int32_t spi;
111         struct secasvar *sav = NULL;
112         size_t taillen;
113         u_int16_t nxt;
114         const struct esp_algorithm *algo;
115         int ivlen;
116         size_t hlen;
117         size_t esplen;
118         int s;
119
120         /* sanity check for alignment. */
121         if (off % 4 != 0 || m->m_pkthdr.len % 4 != 0) {
122                 ipseclog((LOG_ERR, "IPv4 ESP input: packet alignment problem "
123                         "(off=%d, pktlen=%d)\n", off, m->m_pkthdr.len));
124                 ipsecstat.in_inval++;
125                 goto bad;
126         }
127
128         if (m->m_len < off + ESPMAXLEN) {
129                 m = m_pullup(m, off + ESPMAXLEN);
130                 if (!m) {
131                         ipseclog((LOG_DEBUG,
132                             "IPv4 ESP input: can't pullup in esp4_input\n"));
133                         ipsecstat.in_inval++;
134                         goto bad;
135                 }
136         }
137
138         ip = mtod(m, struct ip *);
139         esp = (struct esp *)(((u_int8_t *)ip) + off);
140 #ifdef _IP_VHL
141         hlen = IP_VHL_HL(ip->ip_vhl) << 2;
142 #else
143         hlen = ip->ip_hl << 2;
144 #endif
145
146         /* find the sassoc. */
147         spi = esp->esp_spi;
148
149         if ((sav = key_allocsa(AF_INET,
150                               (caddr_t)&ip->ip_src, (caddr_t)&ip->ip_dst,
151                               IPPROTO_ESP, spi)) == 0) {
152                 ipseclog((LOG_WARNING,
153                     "IPv4 ESP input: no key association found for spi %u\n",
154                     (u_int32_t)ntohl(spi)));
155                 ipsecstat.in_nosa++;
156                 goto bad;
157         }
158         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
159                 printf("DP esp4_input called to allocate SA:%p\n", sav));
160         if (sav->state != SADB_SASTATE_MATURE
161          && sav->state != SADB_SASTATE_DYING) {
162                 ipseclog((LOG_DEBUG,
163                     "IPv4 ESP input: non-mature/dying SA found for spi %u\n",
164                     (u_int32_t)ntohl(spi)));
165                 ipsecstat.in_badspi++;
166                 goto bad;
167         }
168         algo = esp_algorithm_lookup(sav->alg_enc);
169         if (!algo) {
170                 ipseclog((LOG_DEBUG, "IPv4 ESP input: "
171                     "unsupported encryption algorithm for spi %u\n",
172                     (u_int32_t)ntohl(spi)));
173                 ipsecstat.in_badspi++;
174                 goto bad;
175         }
176
177         /* check if we have proper ivlen information */
178         ivlen = sav->ivlen;
179         if (ivlen < 0) {
180                 ipseclog((LOG_ERR, "inproper ivlen in IPv4 ESP input: %s %s\n",
181                     ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
182                 ipsecstat.in_inval++;
183                 goto bad;
184         }
185
186         if (!((sav->flags & SADB_X_EXT_OLD) == 0 && sav->replay
187          && (sav->alg_auth && sav->key_auth)))
188                 goto noreplaycheck;
189
190         if (sav->alg_auth == SADB_X_AALG_NULL ||
191             sav->alg_auth == SADB_AALG_NONE)
192                 goto noreplaycheck;
193
194         /*
195          * check for sequence number.
196          */
197         if (ipsec_chkreplay(ntohl(((struct newesp *)esp)->esp_seq), sav))
198                 ; /* okey */
199         else {
200                 ipsecstat.in_espreplay++;
201                 ipseclog((LOG_WARNING,
202                     "replay packet in IPv4 ESP input: %s %s\n",
203                     ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
204                 goto bad;
205         }
206
207         /* check ICV */
208     {
209         u_char sum0[AH_MAXSUMSIZE];
210         u_char sum[AH_MAXSUMSIZE];
211         const struct ah_algorithm *sumalgo;
212         size_t siz;
213
214         sumalgo = ah_algorithm_lookup(sav->alg_auth);
215         if (!sumalgo)
216                 goto noreplaycheck;
217         siz = (((*sumalgo->sumsiz)(sav) + 3) & ~(4 - 1));
218         if (m->m_pkthdr.len < off + ESPMAXLEN + siz) {
219                 ipsecstat.in_inval++;
220                 goto bad;
221         }
222         if (AH_MAXSUMSIZE < siz) {
223                 ipseclog((LOG_DEBUG,
224                     "internal error: AH_MAXSUMSIZE must be larger than %lu\n",
225                     (u_long)siz));
226                 ipsecstat.in_inval++;
227                 goto bad;
228         }
229
230         m_copydata(m, m->m_pkthdr.len - siz, siz, &sum0[0]);
231
232         if (esp_auth(m, off, m->m_pkthdr.len - off - siz, sav, sum)) {
233                 ipseclog((LOG_WARNING, "auth fail in IPv4 ESP input: %s %s\n",
234                     ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
235                 ipsecstat.in_espauthfail++;
236                 goto bad;
237         }
238
239         if (bcmp(sum0, sum, siz) != 0) {
240                 ipseclog((LOG_WARNING, "auth fail in IPv4 ESP input: %s %s\n",
241                     ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
242                 ipsecstat.in_espauthfail++;
243                 goto bad;
244         }
245
246         /* strip off the authentication data */
247         m_adj(m, -siz);
248         ip = mtod(m, struct ip *);
249 #ifdef IPLEN_FLIPPED
250         ip->ip_len = ip->ip_len - siz;
251 #else
252         ip->ip_len = htons(ntohs(ip->ip_len) - siz);
253 #endif
254         m->m_flags |= M_AUTHIPDGM;
255         ipsecstat.in_espauthsucc++;
256     }
257
258         /*
259          * update sequence number.
260          */
261         if ((sav->flags & SADB_X_EXT_OLD) == 0 && sav->replay) {
262                 if (ipsec_updatereplay(ntohl(((struct newesp *)esp)->esp_seq), sav)) {
263                         ipsecstat.in_espreplay++;
264                         goto bad;
265                 }
266         }
267
268 noreplaycheck:
269
270         /* process main esp header. */
271         if (sav->flags & SADB_X_EXT_OLD) {
272                 /* RFC 1827 */
273                 esplen = sizeof(struct esp);
274         } else {
275                 /* RFC 2406 */
276                 if (sav->flags & SADB_X_EXT_DERIV)
277                         esplen = sizeof(struct esp);
278                 else
279                         esplen = sizeof(struct newesp);
280         }
281
282         if (m->m_pkthdr.len < off + esplen + ivlen + sizeof(esptail)) {
283                 ipseclog((LOG_WARNING,
284                     "IPv4 ESP input: packet too short\n"));
285                 ipsecstat.in_inval++;
286                 goto bad;
287         }
288
289         if (m->m_len < off + esplen + ivlen) {
290                 m = m_pullup(m, off + esplen + ivlen);
291                 if (!m) {
292                         ipseclog((LOG_DEBUG,
293                             "IPv4 ESP input: can't pullup in esp4_input\n"));
294                         ipsecstat.in_inval++;
295                         goto bad;
296                 }
297         }
298
299         /*
300          * pre-compute and cache intermediate key
301          */
302         if (esp_schedule(algo, sav) != 0) {
303                 ipsecstat.in_inval++;
304                 goto bad;
305         }
306
307         /*
308          * decrypt the packet.
309          */
310         if (!algo->decrypt)
311                 panic("internal error: no decrypt function");
312         if ((*algo->decrypt)(m, off, sav, algo, ivlen)) {
313                 /* m is already freed */
314                 m = NULL;
315                 ipseclog((LOG_ERR, "decrypt fail in IPv4 ESP input: %s\n",
316                     ipsec_logsastr(sav)));
317                 ipsecstat.in_inval++;
318                 goto bad;
319         }
320         ipsecstat.in_esphist[sav->alg_enc]++;
321
322         m->m_flags |= M_DECRYPTED;
323
324         /*
325          * find the trailer of the ESP.
326          */
327         m_copydata(m, m->m_pkthdr.len - sizeof(esptail), sizeof(esptail),
328              (caddr_t)&esptail);
329         nxt = esptail.esp_nxt;
330         taillen = esptail.esp_padlen + sizeof(esptail);
331
332         if (m->m_pkthdr.len < taillen
333          || m->m_pkthdr.len - taillen < hlen) { /* ? */
334                 ipseclog((LOG_WARNING,
335                     "bad pad length in IPv4 ESP input: %s %s\n",
336                     ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
337                 ipsecstat.in_inval++;
338                 goto bad;
339         }
340
341         /* strip off the trailing pad area. */
342         m_adj(m, -taillen);
343
344 #ifdef IPLEN_FLIPPED
345         ip->ip_len = ip->ip_len - taillen;
346 #else
347         ip->ip_len = htons(ntohs(ip->ip_len) - taillen);
348 #endif
349
350         /* was it transmitted over the IPsec tunnel SA? */
351         if (ipsec4_tunnel_validate(m, off + esplen + ivlen, nxt, sav)) {
352                 /*
353                  * strip off all the headers that precedes ESP header.
354                  *      IP4 xx ESP IP4' payload -> IP4' payload
355                  *
356                  * XXX more sanity checks
357                  * XXX relationship with gif?
358                  */
359                 u_int8_t tos;
360
361                 tos = ip->ip_tos;
362                 m_adj(m, off + esplen + ivlen);
363                 if (m->m_len < sizeof(*ip)) {
364                         m = m_pullup(m, sizeof(*ip));
365                         if (!m) {
366                                 ipsecstat.in_inval++;
367                                 goto bad;
368                         }
369                 }
370                 ip = mtod(m, struct ip *);
371                 /* ECN consideration. */
372                 ip_ecn_egress(ip4_ipsec_ecn, &tos, &ip->ip_tos);
373                 if (!key_checktunnelsanity(sav, AF_INET,
374                             (caddr_t)&ip->ip_src, (caddr_t)&ip->ip_dst)) {
375                         ipseclog((LOG_ERR, "ipsec tunnel address mismatch "
376                             "in IPv4 ESP input: %s %s\n",
377                             ipsec4_logpacketstr(ip, spi), ipsec_logsastr(sav)));
378                         ipsecstat.in_inval++;
379                         goto bad;
380                 }
381
382                 key_sa_recordxfer(sav, m);
383                 if (ipsec_addhist(m, IPPROTO_ESP, spi) != 0 ||
384                     ipsec_addhist(m, IPPROTO_IPV4, 0) != 0) {
385                         ipsecstat.in_nomem++;
386                         goto bad;
387                 }
388
389                 s = splimp();
390                 if (IF_QFULL(&ipintrq)) {
391                         ipsecstat.in_inval++;
392                         splx(s);
393                         goto bad;
394                 }
395                 IF_ENQUEUE(&ipintrq, m);
396                 m = NULL;
397                 schednetisr(NETISR_IP); /* can be skipped but to make sure */
398                 splx(s);
399                 nxt = IPPROTO_DONE;
400         } else {
401                 /*
402                  * strip off ESP header and IV.
403                  * even in m_pulldown case, we need to strip off ESP so that
404                  * we can always compute checksum for AH correctly.
405                  */
406                 size_t stripsiz;
407
408                 stripsiz = esplen + ivlen;
409
410                 ip = mtod(m, struct ip *);
411                 ovbcopy((caddr_t)ip, (caddr_t)(((u_char *)ip) + stripsiz), off);
412                 m->m_data += stripsiz;
413                 m->m_len -= stripsiz;
414                 m->m_pkthdr.len -= stripsiz;
415
416                 ip = mtod(m, struct ip *);
417 #ifdef IPLEN_FLIPPED
418                 ip->ip_len = ip->ip_len - stripsiz;
419 #else
420                 ip->ip_len = htons(ntohs(ip->ip_len) - stripsiz);
421 #endif
422                 ip->ip_p = nxt;
423
424                 key_sa_recordxfer(sav, m);
425                 if (ipsec_addhist(m, IPPROTO_ESP, spi) != 0) {
426                         ipsecstat.in_nomem++;
427                         goto bad;
428                 }
429
430                 if (nxt != IPPROTO_DONE) {
431                         if ((inetsw[ip_protox[nxt]].pr_flags & PR_LASTHDR) != 0 &&
432                             ipsec4_in_reject(m, NULL)) {
433                                 ipsecstat.in_polvio++;
434                                 goto bad;
435                         }
436                         (*inetsw[ip_protox[nxt]].pr_input)(m, off, nxt);
437                 } else
438                         m_freem(m);
439                 m = NULL;
440         }
441
442         if (sav) {
443                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
444                         printf("DP esp4_input call free SA:%p\n", sav));
445                 key_freesav(sav);
446         }
447         ipsecstat.in_success++;
448         return;
449
450 bad:
451         if (sav) {
452                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
453                         printf("DP esp4_input call free SA:%p\n", sav));
454                 key_freesav(sav);
455         }
456         if (m)
457                 m_freem(m);
458         return;
459 }
460 #endif /* INET */
461
462 #ifdef INET6
463 int
464 esp6_input(mp, offp, proto)
465         struct mbuf **mp;
466         int *offp, proto;
467 {
468         struct mbuf *m = *mp;
469         int off = *offp;
470         struct ip6_hdr *ip6;
471         struct esp *esp;
472         struct esptail esptail;
473         u_int32_t spi;
474         struct secasvar *sav = NULL;
475         size_t taillen;
476         u_int16_t nxt;
477         const struct esp_algorithm *algo;
478         int ivlen;
479         size_t esplen;
480         int s;
481
482         /* sanity check for alignment. */
483         if (off % 4 != 0 || m->m_pkthdr.len % 4 != 0) {
484                 ipseclog((LOG_ERR, "IPv6 ESP input: packet alignment problem "
485                         "(off=%d, pktlen=%d)\n", off, m->m_pkthdr.len));
486                 ipsec6stat.in_inval++;
487                 goto bad;
488         }
489
490 #ifndef PULLDOWN_TEST
491         IP6_EXTHDR_CHECK(m, off, ESPMAXLEN, IPPROTO_DONE);
492         esp = (struct esp *)(mtod(m, caddr_t) + off);
493 #else
494         IP6_EXTHDR_GET(esp, struct esp *, m, off, ESPMAXLEN);
495         if (esp == NULL) {
496                 ipsec6stat.in_inval++;
497                 return IPPROTO_DONE;
498         }
499 #endif
500         ip6 = mtod(m, struct ip6_hdr *);
501
502         if (ntohs(ip6->ip6_plen) == 0) {
503                 ipseclog((LOG_ERR, "IPv6 ESP input: "
504                     "ESP with IPv6 jumbogram is not supported.\n"));
505                 ipsec6stat.in_inval++;
506                 goto bad;
507         }
508
509         /* find the sassoc. */
510         spi = esp->esp_spi;
511
512         if ((sav = key_allocsa(AF_INET6,
513                               (caddr_t)&ip6->ip6_src, (caddr_t)&ip6->ip6_dst,
514                               IPPROTO_ESP, spi)) == 0) {
515                 ipseclog((LOG_WARNING,
516                     "IPv6 ESP input: no key association found for spi %u\n",
517                     (u_int32_t)ntohl(spi)));
518                 ipsec6stat.in_nosa++;
519                 goto bad;
520         }
521         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
522                 printf("DP esp6_input called to allocate SA:%p\n", sav));
523         if (sav->state != SADB_SASTATE_MATURE
524          && sav->state != SADB_SASTATE_DYING) {
525                 ipseclog((LOG_DEBUG,
526                     "IPv6 ESP input: non-mature/dying SA found for spi %u\n",
527                     (u_int32_t)ntohl(spi)));
528                 ipsec6stat.in_badspi++;
529                 goto bad;
530         }
531         algo = esp_algorithm_lookup(sav->alg_enc);
532         if (!algo) {
533                 ipseclog((LOG_DEBUG, "IPv6 ESP input: "
534                     "unsupported encryption algorithm for spi %u\n",
535                     (u_int32_t)ntohl(spi)));
536                 ipsec6stat.in_badspi++;
537                 goto bad;
538         }
539
540         /* check if we have proper ivlen information */
541         ivlen = sav->ivlen;
542         if (ivlen < 0) {
543                 ipseclog((LOG_ERR, "inproper ivlen in IPv6 ESP input: %s %s\n",
544                     ipsec6_logpacketstr(ip6, spi), ipsec_logsastr(sav)));
545                 ipsec6stat.in_badspi++;
546                 goto bad;
547         }
548
549         if (!((sav->flags & SADB_X_EXT_OLD) == 0 && sav->replay
550          && (sav->alg_auth && sav->key_auth)))
551                 goto noreplaycheck;
552
553         if (sav->alg_auth == SADB_X_AALG_NULL ||
554             sav->alg_auth == SADB_AALG_NONE)
555                 goto noreplaycheck;
556
557         /*
558          * check for sequence number.
559          */
560         if (ipsec_chkreplay(ntohl(((struct newesp *)esp)->esp_seq), sav))
561                 ; /* okey */
562         else {
563                 ipsec6stat.in_espreplay++;
564                 ipseclog((LOG_WARNING,
565                     "replay packet in IPv6 ESP input: %s %s\n",
566                     ipsec6_logpacketstr(ip6, spi), ipsec_logsastr(sav)));
567                 goto bad;
568         }
569
570         /* check ICV */
571     {
572         u_char sum0[AH_MAXSUMSIZE];
573         u_char sum[AH_MAXSUMSIZE];
574         const struct ah_algorithm *sumalgo;
575         size_t siz;
576
577         sumalgo = ah_algorithm_lookup(sav->alg_auth);
578         if (!sumalgo)
579                 goto noreplaycheck;
580         siz = (((*sumalgo->sumsiz)(sav) + 3) & ~(4 - 1));
581         if (m->m_pkthdr.len < off + ESPMAXLEN + siz) {
582                 ipsecstat.in_inval++;
583                 goto bad;
584         }
585         if (AH_MAXSUMSIZE < siz) {
586                 ipseclog((LOG_DEBUG,
587                     "internal error: AH_MAXSUMSIZE must be larger than %lu\n",
588                     (u_long)siz));
589                 ipsec6stat.in_inval++;
590                 goto bad;
591         }
592
593         m_copydata(m, m->m_pkthdr.len - siz, siz, &sum0[0]);
594
595         if (esp_auth(m, off, m->m_pkthdr.len - off - siz, sav, sum)) {
596                 ipseclog((LOG_WARNING, "auth fail in IPv6 ESP input: %s %s\n",
597                     ipsec6_logpacketstr(ip6, spi), ipsec_logsastr(sav)));
598                 ipsec6stat.in_espauthfail++;
599                 goto bad;
600         }
601
602         if (bcmp(sum0, sum, siz) != 0) {
603                 ipseclog((LOG_WARNING, "auth fail in IPv6 ESP input: %s %s\n",
604                     ipsec6_logpacketstr(ip6, spi), ipsec_logsastr(sav)));
605                 ipsec6stat.in_espauthfail++;
606                 goto bad;
607         }
608
609         /* strip off the authentication data */
610         m_adj(m, -siz);
611         ip6 = mtod(m, struct ip6_hdr *);
612         ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - siz);
613
614         m->m_flags |= M_AUTHIPDGM;
615         ipsec6stat.in_espauthsucc++;
616     }
617
618         /*
619          * update sequence number.
620          */
621         if ((sav->flags & SADB_X_EXT_OLD) == 0 && sav->replay) {
622                 if (ipsec_updatereplay(ntohl(((struct newesp *)esp)->esp_seq), sav)) {
623                         ipsec6stat.in_espreplay++;
624                         goto bad;
625                 }
626         }
627
628 noreplaycheck:
629
630         /* process main esp header. */
631         if (sav->flags & SADB_X_EXT_OLD) {
632                 /* RFC 1827 */
633                 esplen = sizeof(struct esp);
634         } else {
635                 /* RFC 2406 */
636                 if (sav->flags & SADB_X_EXT_DERIV)
637                         esplen = sizeof(struct esp);
638                 else
639                         esplen = sizeof(struct newesp);
640         }
641
642         if (m->m_pkthdr.len < off + esplen + ivlen + sizeof(esptail)) {
643                 ipseclog((LOG_WARNING,
644                     "IPv6 ESP input: packet too short\n"));
645                 ipsec6stat.in_inval++;
646                 goto bad;
647         }
648
649 #ifndef PULLDOWN_TEST
650         IP6_EXTHDR_CHECK(m, off, esplen + ivlen, IPPROTO_DONE); /* XXX */
651 #else
652         IP6_EXTHDR_GET(esp, struct esp *, m, off, esplen + ivlen);
653         if (esp == NULL) {
654                 ipsec6stat.in_inval++;
655                 m = NULL;
656                 goto bad;
657         }
658 #endif
659         ip6 = mtod(m, struct ip6_hdr *);        /* set it again just in case */
660
661         /*
662          * pre-compute and cache intermediate key
663          */
664         if (esp_schedule(algo, sav) != 0) {
665                 ipsec6stat.in_inval++;
666                 goto bad;
667         }
668
669         /*
670          * decrypt the packet.
671          */
672         if (!algo->decrypt)
673                 panic("internal error: no decrypt function");
674         if ((*algo->decrypt)(m, off, sav, algo, ivlen)) {
675                 /* m is already freed */
676                 m = NULL;
677                 ipseclog((LOG_ERR, "decrypt fail in IPv6 ESP input: %s\n",
678                     ipsec_logsastr(sav)));
679                 ipsec6stat.in_inval++;
680                 goto bad;
681         }
682         ipsec6stat.in_esphist[sav->alg_enc]++;
683
684         m->m_flags |= M_DECRYPTED;
685
686         /*
687          * find the trailer of the ESP.
688          */
689         m_copydata(m, m->m_pkthdr.len - sizeof(esptail), sizeof(esptail),
690              (caddr_t)&esptail);
691         nxt = esptail.esp_nxt;
692         taillen = esptail.esp_padlen + sizeof(esptail);
693
694         if (m->m_pkthdr.len < taillen
695          || m->m_pkthdr.len - taillen < sizeof(struct ip6_hdr)) {       /* ? */
696                 ipseclog((LOG_WARNING,
697                     "bad pad length in IPv6 ESP input: %s %s\n",
698                     ipsec6_logpacketstr(ip6, spi), ipsec_logsastr(sav)));
699                 ipsec6stat.in_inval++;
700                 goto bad;
701         }
702
703         /* strip off the trailing pad area. */
704         m_adj(m, -taillen);
705
706         ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - taillen);
707
708         /* was it transmitted over the IPsec tunnel SA? */
709         if (ipsec6_tunnel_validate(m, off + esplen + ivlen, nxt, sav)) {
710                 /*
711                  * strip off all the headers that precedes ESP header.
712                  *      IP6 xx ESP IP6' payload -> IP6' payload
713                  *
714                  * XXX more sanity checks
715                  * XXX relationship with gif?
716                  */
717                 u_int32_t flowinfo;     /* net endian */
718                 flowinfo = ip6->ip6_flow;
719                 m_adj(m, off + esplen + ivlen);
720                 if (m->m_len < sizeof(*ip6)) {
721 #ifndef PULLDOWN_TEST
722                         /*
723                          * m_pullup is prohibited in KAME IPv6 input processing
724                          * but there's no other way!
725                          */
726 #else
727                         /* okay to pullup in m_pulldown style */
728 #endif
729                         m = m_pullup(m, sizeof(*ip6));
730                         if (!m) {
731                                 ipsec6stat.in_inval++;
732                                 goto bad;
733                         }
734                 }
735                 ip6 = mtod(m, struct ip6_hdr *);
736                 /* ECN consideration. */
737                 ip6_ecn_egress(ip6_ipsec_ecn, &flowinfo, &ip6->ip6_flow);
738                 if (!key_checktunnelsanity(sav, AF_INET6,
739                             (caddr_t)&ip6->ip6_src, (caddr_t)&ip6->ip6_dst)) {
740                         ipseclog((LOG_ERR, "ipsec tunnel address mismatch "
741                             "in IPv6 ESP input: %s %s\n",
742                             ipsec6_logpacketstr(ip6, spi),
743                             ipsec_logsastr(sav)));
744                         ipsec6stat.in_inval++;
745                         goto bad;
746                 }
747
748                 key_sa_recordxfer(sav, m);
749                 if (ipsec_addhist(m, IPPROTO_ESP, spi) != 0 || 
750                     ipsec_addhist(m, IPPROTO_IPV6, 0) != 0) {
751                         ipsec6stat.in_nomem++;
752                         goto bad;
753                 }
754
755                 s = splimp();
756                 if (IF_QFULL(&ip6intrq)) {
757                         ipsec6stat.in_inval++;
758                         splx(s);
759                         goto bad;
760                 }
761                 IF_ENQUEUE(&ip6intrq, m);
762                 m = NULL;
763                 schednetisr(NETISR_IPV6); /* can be skipped but to make sure */
764                 splx(s);
765                 nxt = IPPROTO_DONE;
766         } else {
767                 /*
768                  * strip off ESP header and IV.
769                  * even in m_pulldown case, we need to strip off ESP so that
770                  * we can always compute checksum for AH correctly.
771                  */
772                 size_t stripsiz;
773                 char *prvnxtp;
774
775                 /*
776                  * Set the next header field of the previous header correctly.
777                  */
778                 prvnxtp = ip6_get_prevhdr(m, off); /* XXX */
779                 *prvnxtp = nxt;
780
781                 stripsiz = esplen + ivlen;
782
783                 ip6 = mtod(m, struct ip6_hdr *);
784                 if (m->m_len >= stripsiz + off) {
785                         ovbcopy((caddr_t)ip6, ((caddr_t)ip6) + stripsiz, off);
786                         m->m_data += stripsiz;
787                         m->m_len -= stripsiz;
788                         m->m_pkthdr.len -= stripsiz;
789                 } else {
790                         /*
791                          * this comes with no copy if the boundary is on
792                          * cluster
793                          */
794                         struct mbuf *n;
795
796                         n = m_split(m, off, M_DONTWAIT);
797                         if (n == NULL) {
798                                 /* m is retained by m_split */
799                                 goto bad;
800                         }
801                         m_adj(n, stripsiz);
802                         m_cat(m, n);
803                         /* m_cat does not update m_pkthdr.len */
804                         m->m_pkthdr.len += n->m_pkthdr.len;
805                 }
806
807 #ifndef PULLDOWN_TEST
808                 /*
809                  * KAME requires that the packet to be contiguous on the
810                  * mbuf.  We need to make that sure.
811                  * this kind of code should be avoided.
812                  * XXX other conditions to avoid running this part?
813                  */
814                 if (m->m_len != m->m_pkthdr.len) {
815                         struct mbuf *n = NULL;
816                         int maxlen;
817
818                         MGETHDR(n, M_DONTWAIT, MT_HEADER);
819                         maxlen = MHLEN;
820                         if (n)
821                                 M_MOVE_PKTHDR(n, m);
822                         if (n && n->m_pkthdr.len > maxlen) {
823                                 MCLGET(n, M_DONTWAIT);
824                                 maxlen = MCLBYTES;
825                                 if ((n->m_flags & M_EXT) == 0) {
826                                         m_free(n);
827                                         n = NULL;
828                                 }
829                         }
830                         if (!n) {
831                                 printf("esp6_input: mbuf allocation failed\n");
832                                 goto bad;
833                         }
834
835                         if (n->m_pkthdr.len <= maxlen) {
836                                 m_copydata(m, 0, n->m_pkthdr.len, mtod(n, caddr_t));
837                                 n->m_len = n->m_pkthdr.len;
838                                 n->m_next = NULL;
839                                 m_freem(m);
840                         } else {
841                                 m_copydata(m, 0, maxlen, mtod(n, caddr_t));
842                                 n->m_len = maxlen;
843                                 n->m_next = m;
844                                 m_adj(m, maxlen);
845                         }
846                         m = n;
847                 }
848 #endif
849
850                 ip6 = mtod(m, struct ip6_hdr *);
851                 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - stripsiz);
852
853                 key_sa_recordxfer(sav, m);
854                 if (ipsec_addhist(m, IPPROTO_ESP, spi) != 0) {
855                         ipsec6stat.in_nomem++;
856                         goto bad;
857                 }
858         }
859
860         *offp = off;
861         *mp = m;
862
863         if (sav) {
864                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
865                         printf("DP esp6_input call free SA:%p\n", sav));
866                 key_freesav(sav);
867         }
868         ipsec6stat.in_success++;
869         return nxt;
870
871 bad:
872         if (sav) {
873                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
874                         printf("DP esp6_input call free SA:%p\n", sav));
875                 key_freesav(sav);
876         }
877         if (m)
878                 m_freem(m);
879         return IPPROTO_DONE;
880 }
881
882 void
883 esp6_ctlinput(cmd, sa, d)
884         int cmd;
885         struct sockaddr *sa;
886         void *d;
887 {
888         const struct newesp *espp;
889         struct newesp esp;
890         struct ip6ctlparam *ip6cp = NULL, ip6cp1;
891         struct secasvar *sav;
892         struct ip6_hdr *ip6;
893         struct mbuf *m;
894         int off;
895         struct sockaddr_in6 *sa6_src, *sa6_dst;
896
897         if (sa->sa_family != AF_INET6 ||
898             sa->sa_len != sizeof(struct sockaddr_in6))
899                 return;
900         if ((unsigned)cmd >= PRC_NCMDS)
901                 return;
902
903         /* if the parameter is from icmp6, decode it. */
904         if (d != NULL) {
905                 ip6cp = (struct ip6ctlparam *)d;
906                 m = ip6cp->ip6c_m;
907                 ip6 = ip6cp->ip6c_ip6;
908                 off = ip6cp->ip6c_off;
909         } else {
910                 m = NULL;
911                 ip6 = NULL;
912                 off = 0; /* fix warning */
913         }
914
915         if (ip6) {
916                 /*
917                  * Notify the error to all possible sockets via pfctlinput2.
918                  * Since the upper layer information (such as protocol type,
919                  * source and destination ports) is embedded in the encrypted
920                  * data and might have been cut, we can't directly call
921                  * an upper layer ctlinput function. However, the pcbnotify
922                  * function will consider source and destination addresses
923                  * as well as the flow info value, and may be able to find
924                  * some PCB that should be notified.
925                  * Although pfctlinput2 will call esp6_ctlinput(), there is
926                  * no possibility of an infinite loop of function calls,
927                  * because we don't pass the inner IPv6 header.
928                  */
929                 bzero(&ip6cp1, sizeof(ip6cp1));
930                 ip6cp1.ip6c_src = ip6cp->ip6c_src;
931                 pfctlinput2(cmd, sa, (void *)&ip6cp1);
932
933                 /*
934                  * Then go to special cases that need ESP header information.
935                  * XXX: We assume that when ip6 is non NULL,
936                  * M and OFF are valid.
937                  */
938
939                 /* check if we can safely examine src and dst ports */
940                 if (m->m_pkthdr.len < off + sizeof(esp))
941                         return;
942
943                 if (m->m_len < off + sizeof(esp)) {
944                         /*
945                          * this should be rare case,
946                          * so we compromise on this copy...
947                          */
948                         m_copydata(m, off, sizeof(esp), (caddr_t)&esp);
949                         espp = &esp;
950                 } else
951                         espp = (struct newesp*)(mtod(m, caddr_t) + off);
952
953                 if (cmd == PRC_MSGSIZE) {
954                         int valid = 0;
955
956                         /*
957                          * Check to see if we have a valid SA corresponding to
958                          * the address in the ICMP message payload.
959                          */
960                         sa6_src = ip6cp->ip6c_src;
961                         sa6_dst = (struct sockaddr_in6 *)sa;
962                         sav = key_allocsa(AF_INET6,
963                                           (caddr_t)&sa6_src->sin6_addr,
964                                           (caddr_t)&sa6_dst->sin6_addr,
965                                           IPPROTO_ESP, espp->esp_spi);
966                         if (sav) {
967                                 if (sav->state == SADB_SASTATE_MATURE ||
968                                     sav->state == SADB_SASTATE_DYING)
969                                         valid++;
970                                 key_freesav(sav);
971                         }
972
973                         /* XXX Further validation? */
974
975                         /*
976                          * Depending on the value of "valid" and routing table
977                          * size (mtudisc_{hi,lo}wat), we will:
978                          * - recalcurate the new MTU and create the
979                          *   corresponding routing entry, or
980                          * - ignore the MTU change notification.
981                          */
982                         icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
983                 }
984         } else {
985                 /* we normally notify any pcb here */
986         }
987 }
988 #endif /* INET6 */