1 //==========================================================================
3 // src/sys/netinet6/esp_output.c
5 //==========================================================================
6 //####BSDCOPYRIGHTBEGIN####
8 // -------------------------------------------
10 // Portions of this software may have been derived from OpenBSD,
11 // FreeBSD or other sources, and are covered by the appropriate
12 // copyright disclaimers included herein.
14 // Portions created by Red Hat are
15 // Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
17 // -------------------------------------------
19 //####BSDCOPYRIGHTEND####
20 //==========================================================================
22 /* $KAME: esp_output.c,v 1.44 2001/07/26 06:53:15 jinmei Exp $ */
25 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
26 * All rights reserved.
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
31 * 1. Redistributions of source code must retain the above copyright
32 * notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 * notice, this list of conditions and the following disclaimer in the
35 * documentation and/or other materials provided with the distribution.
36 * 3. Neither the name of the project nor the names of its contributors
37 * may be used to endorse or promote products derived from this software
38 * without specific prior written permission.
40 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * RFC1827/2406 Encapsulated Security Payload.
57 #include <sys/param.h>
58 #if !(defined(__FreeBSD__) && __FreeBSD__ >= 4)
59 #include <sys/malloc.h>
62 #include <sys/domain.h>
63 #include <sys/protosw.h>
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/errno.h>
70 #include <net/route.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/in_var.h>
78 #include <netinet/ip6.h>
79 #include <netinet6/ip6_var.h>
80 #include <netinet/icmp6.h>
83 #include <netinet6/ipsec.h>
84 #include <netinet6/ah.h>
85 #include <netinet6/esp.h>
86 #include <netkey/key.h>
87 #include <netkey/keydb.h>
89 static int esp_output __P((struct mbuf *, u_char *, struct mbuf *,
90 struct ipsecrequest *, int));
93 * compute ESP header size.
97 struct ipsecrequest *isr;
100 const struct esp_algorithm *algo;
101 const struct ah_algorithm *aalgo;
108 panic("esp_hdrsiz: NULL was passed.\n");
112 if (isr->saidx.proto != IPPROTO_ESP)
113 panic("unsupported mode passed to esp_hdrsiz");
117 if (sav->state != SADB_SASTATE_MATURE
118 && sav->state != SADB_SASTATE_DYING)
121 /* we need transport mode ESP. */
122 algo = esp_algorithm_lookup(sav->alg_enc);
131 * right now we don't calcurate the padding size. simply
132 * treat the padding size as constant, for simplicity.
134 * XXX variable size padding support
136 if (sav->flags & SADB_X_EXT_OLD) {
138 hdrsiz = sizeof(struct esp) + ivlen + 9;
141 aalgo = ah_algorithm_lookup(sav->alg_auth);
142 if (aalgo && sav->replay && sav->key_auth)
143 authlen = (aalgo->sumsiz)(sav);
146 hdrsiz = sizeof(struct newesp) + ivlen + 9 + authlen;
154 * sizeof(struct newesp) > sizeof(struct esp).
155 * esp_max_ivlen() = max ivlen for CBC mode
156 * 9 = (maximum padding length without random padding length)
157 * + (Pad Length field) + (Next Header field).
158 * 16 = maximum ICV we support.
160 return sizeof(struct newesp) + esp_max_ivlen() + 9 + 16;
164 * Modify the packet so that the payload is encrypted.
165 * The mbuf (m) must start with IPv4 or IPv6 header.
166 * On failure, free the given mbuf and return NULL.
171 * IP ......... payload
172 * during the encryption:
173 * m nexthdrp mprev md
175 * IP ............... esp iv payload pad padlen nxthdr
176 * <--><-><------><--------------->
177 * esplen plen extendsiz
181 * <-----------------> espoff
184 esp_output(m, nexthdrp, md, isr, af)
188 struct ipsecrequest *isr;
194 struct esptail *esptail;
195 struct secasvar *sav = isr->sav;
196 const struct esp_algorithm *algo;
199 size_t plen; /* payload length to be encrypted */
205 struct ipsecstat *stat;
221 ipseclog((LOG_ERR, "esp_output: unsupported af %d\n", af));
222 return 0; /* no change at all */
225 /* some sanity check */
226 if ((sav->flags & SADB_X_EXT_OLD) == 0 && !sav->replay) {
233 ip = mtod(m, struct ip *);
234 ipseclog((LOG_DEBUG, "esp4_output: internal error: "
235 "sav->replay is null: %x->%x, SPI=%u\n",
236 (u_int32_t)ntohl(ip->ip_src.s_addr),
237 (u_int32_t)ntohl(ip->ip_dst.s_addr),
238 (u_int32_t)ntohl(sav->spi)));
239 ipsecstat.out_inval++;
245 ipseclog((LOG_DEBUG, "esp6_output: internal error: "
246 "sav->replay is null: SPI=%u\n",
247 (u_int32_t)ntohl(sav->spi)));
248 ipsec6stat.out_inval++;
252 panic("esp_output: should not reach here");
258 algo = esp_algorithm_lookup(sav->alg_enc);
260 ipseclog((LOG_ERR, "esp_output: unsupported algorithm: "
261 "SPI=%u\n", (u_int32_t)ntohl(sav->spi)));
269 panic("invalid ivlen");
275 * XXX inserts ESP header right after IPv4 header. should
276 * chase the header chain.
277 * XXX sequential number
280 struct ip *ip = NULL;
283 struct ip6_hdr *ip6 = NULL;
285 size_t esplen; /* sizeof(struct esp/newesp) */
286 size_t esphlen; /* sizeof(struct esp/newesp) + ivlen */
287 size_t hlen = 0; /* ip header len */
289 if (sav->flags & SADB_X_EXT_OLD) {
291 esplen = sizeof(struct esp);
294 if (sav->flags & SADB_X_EXT_DERIV)
295 esplen = sizeof(struct esp);
297 esplen = sizeof(struct newesp);
299 esphlen = esplen + ivlen;
301 for (mprev = m; mprev && mprev->m_next != md; mprev = mprev->m_next)
303 if (mprev == NULL || mprev->m_next != md) {
304 ipseclog((LOG_DEBUG, "esp%d_output: md is not in chain\n",
311 for (n = md; n; n = n->m_next)
317 ip = mtod(m, struct ip *);
319 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
321 hlen = ip->ip_hl << 2;
327 ip6 = mtod(m, struct ip6_hdr *);
333 /* make the packet over-writable */
334 mprev->m_next = NULL;
335 if ((md = ipsec_copypkt(md)) == NULL) {
342 espoff = m->m_pkthdr.len - plen;
345 * grow the mbuf to accomodate ESP header.
346 * before: IP ... payload
347 * after: IP ... ESP IV payload
349 if (M_LEADINGSPACE(md) < esphlen || (md->m_flags & M_EXT) != 0) {
350 MGET(n, M_DONTWAIT, MT_DATA);
359 m->m_pkthdr.len += esphlen;
360 esp = mtod(n, struct esp *);
362 md->m_len += esphlen;
363 md->m_data -= esphlen;
364 m->m_pkthdr.len += esphlen;
365 esp = mtod(md, struct esp *);
369 *nexthdrp = IPPROTO_ESP;
373 if (esphlen < (IP_MAXPACKET - ntohs(ip->ip_len)))
374 ip->ip_len = htons(ntohs(ip->ip_len) + esphlen);
377 "IPv4 ESP output: size exceeds limit\n"));
378 ipsecstat.out_inval++;
387 /* total packet length will be computed in ip6_output() */
393 /* initialize esp header. */
395 if ((sav->flags & SADB_X_EXT_OLD) == 0) {
397 nesp = (struct newesp *)esp;
398 if (sav->replay->count == ~0) {
399 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
400 /* XXX Is it noisy ? */
401 ipseclog((LOG_WARNING,
402 "replay counter overflowed. %s\n",
403 ipsec_logsastr(sav)));
409 sav->replay->count++;
411 * XXX sequence number must not be cycled, if the SA is
412 * installed by IKE daemon.
414 nesp->esp_seq = htonl(sav->replay->count);
419 * find the last mbuf. make some room for ESP trailer.
422 struct ip *ip = NULL;
430 padbound = algo->padbound;
433 /* ESP packet, including nxthdr field, must be length of 4n */
437 extendsiz = padbound - (plen % padbound);
439 extendsiz = padbound + 1;
445 randpadmax = ip4_esp_randpad;
450 randpadmax = ip6_esp_randpad;
457 if (randpadmax < 0 || plen + extendsiz >= randpadmax)
463 randpadmax = (randpadmax / padbound) * padbound;
464 n = (randpadmax - plen + extendsiz) / padbound;
467 n = (random() % n) * padbound;
472 * make sure we do not pad too much.
473 * MLEN limitation comes from the trailer attachment
475 * 256 limitation comes from sequential padding.
476 * also, the 1-octet length field in ESP trailer imposes
477 * limitation (but is less strict than sequential padding
478 * as length field do not count the last 2 octets).
480 if (extendsiz + n <= MLEN && extendsiz + n < 256)
485 if (extendsiz > MLEN || extendsiz >= 256)
486 panic("extendsiz too big in esp_output");
494 * if M_EXT, the external mbuf data may be shared among
495 * two consequtive TCP packets, and it may be unsafe to use the
498 if (!(n->m_flags & M_EXT) && extendsiz < M_TRAILINGSPACE(n)) {
499 extend = mtod(n, u_char *) + n->m_len;
500 n->m_len += extendsiz;
501 m->m_pkthdr.len += extendsiz;
505 MGET(nn, M_DONTWAIT, MT_DATA);
507 ipseclog((LOG_DEBUG, "esp%d_output: can't alloc mbuf",
513 extend = mtod(nn, u_char *);
514 nn->m_len = extendsiz;
518 m->m_pkthdr.len += extendsiz;
520 switch (sav->flags & SADB_X_EXT_PMASK) {
521 case SADB_X_EXT_PRAND:
522 key_randomfill(extend, extendsiz);
524 case SADB_X_EXT_PZERO:
525 bzero(extend, extendsiz);
527 case SADB_X_EXT_PSEQ:
528 for (i = 0; i < extendsiz; i++)
529 extend[i] = (i + 1) & 0xff;
533 /* initialize esp trailer. */
534 esptail = (struct esptail *)
535 (mtod(n, u_int8_t *) + n->m_len - sizeof(struct esptail));
536 esptail->esp_nxt = nxt;
537 esptail->esp_padlen = extendsiz - 2;
539 /* modify IP header (for ESP header part only) */
543 ip = mtod(m, struct ip *);
544 if (extendsiz < (IP_MAXPACKET - ntohs(ip->ip_len)))
545 ip->ip_len = htons(ntohs(ip->ip_len) + extendsiz);
548 "IPv4 ESP output: size exceeds limit\n"));
549 ipsecstat.out_inval++;
558 /* total packet length will be computed in ip6_output() */
565 * pre-compute and cache intermediate key
567 error = esp_schedule(algo, sav);
575 * encrypt the packet, based on security association
576 * and the algorithm specified.
579 panic("internal error: no encrypt function");
580 if ((*algo->encrypt)(m, espoff, plen + extendsiz, sav, algo, ivlen)) {
581 /* m is already freed */
582 ipseclog((LOG_ERR, "packet encryption failure\n"));
589 * calculate ICV if required.
595 if (sav->key_auth == SADB_AALG_NONE)
599 const struct ah_algorithm *aalgo;
600 u_char authbuf[AH_MAXSUMSIZE];
608 aalgo = ah_algorithm_lookup(sav->alg_auth);
611 siz = ((aalgo->sumsiz)(sav) + 3) & ~(4 - 1);
612 if (AH_MAXSUMSIZE < siz)
613 panic("assertion failed for AH_MAXSUMSIZE");
615 if (esp_auth(m, espoff, m->m_pkthdr.len - espoff, sav, authbuf)) {
616 ipseclog((LOG_ERR, "ESP checksum generation failure\n"));
627 if (!(n->m_flags & M_EXT) && siz < M_TRAILINGSPACE(n)) { /* XXX */
629 m->m_pkthdr.len += siz;
630 p = mtod(n, u_char *) + n->m_len - siz;
634 MGET(nn, M_DONTWAIT, MT_DATA);
636 ipseclog((LOG_DEBUG, "can't alloc mbuf in esp%d_output",
646 m->m_pkthdr.len += siz;
647 p = mtod(nn, u_char *);
649 bcopy(authbuf, p, siz);
651 /* modify IP header (for ESP header part only) */
655 ip = mtod(m, struct ip *);
656 if (siz < (IP_MAXPACKET - ntohs(ip->ip_len)))
657 ip->ip_len = htons(ntohs(ip->ip_len) + siz);
660 "IPv4 ESP output: size exceeds limit\n"));
661 ipsecstat.out_inval++;
670 /* total packet length will be computed in ip6_output() */
679 "NULL mbuf after encryption in esp%d_output", afnumber));
682 stat->out_esphist[sav->alg_enc]++;
683 key_sa_recordxfer(sav, m);
690 panic("something bad in esp_output");
698 struct ipsecrequest *isr;
701 if (m->m_len < sizeof(struct ip)) {
702 ipseclog((LOG_DEBUG, "esp4_output: first mbuf too short\n"));
706 ip = mtod(m, struct ip *);
707 /* XXX assumes that m->m_next points to payload */
708 return esp_output(m, &ip->ip_p, m->m_next, isr, AF_INET);
714 esp6_output(m, nexthdrp, md, isr)
718 struct ipsecrequest *isr;
720 if (m->m_len < sizeof(struct ip6_hdr)) {
721 ipseclog((LOG_DEBUG, "esp6_output: first mbuf too short\n"));
725 return esp_output(m, nexthdrp, md, isr, AF_INET6);