]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/netipsec/xform_esp.c
MFC r238980:
[FreeBSD/stable/8.git] / sys / netipsec / xform_esp.c
1 /*      $FreeBSD$       */
2 /*      $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
3 /*-
4  * The authors of this code are John Ioannidis (ji@tla.org),
5  * Angelos D. Keromytis (kermit@csd.uch.gr) and
6  * Niels Provos (provos@physnet.uni-hamburg.de).
7  *
8  * The original version of this code was written by John Ioannidis
9  * for BSD/OS in Athens, Greece, in November 1995.
10  *
11  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12  * by Angelos D. Keromytis.
13  *
14  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
15  * and Niels Provos.
16  *
17  * Additional features in 1999 by Angelos D. Keromytis.
18  *
19  * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20  * Angelos D. Keromytis and Niels Provos.
21  * Copyright (c) 2001 Angelos D. Keromytis.
22  *
23  * Permission to use, copy, and modify this software with or without fee
24  * is hereby granted, provided that this entire notice is included in
25  * all copies of any software which is or includes a copy or
26  * modification of this software.
27  * You may use this code under the GNU public license if you so wish. Please
28  * contribute changes back to the authors under this freer than GPL license
29  * so that we may further the use of strong encryption without limitations to
30  * all.
31  *
32  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36  * PURPOSE.
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/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/kernel.h>
47 #include <sys/random.h>
48 #include <sys/sysctl.h>
49
50 #include <net/if.h>
51 #include <net/vnet.h>
52
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip_ecn.h>
57 #include <netinet/ip6.h>
58
59 #include <net/route.h>
60 #include <netipsec/ipsec.h>
61 #include <netipsec/ah.h>
62 #include <netipsec/ah_var.h>
63 #include <netipsec/esp.h>
64 #include <netipsec/esp_var.h>
65 #include <netipsec/xform.h>
66
67 #ifdef INET6
68 #include <netinet6/ip6_var.h>
69 #include <netipsec/ipsec6.h>
70 #include <netinet6/ip6_ecn.h>
71 #endif
72
73 #include <netipsec/key.h>
74 #include <netipsec/key_debug.h>
75
76 #include <opencrypto/cryptodev.h>
77 #include <opencrypto/xform.h>
78
79 VNET_DEFINE(int, esp_enable) = 1;
80 VNET_DEFINE(struct espstat, espstat);
81
82 SYSCTL_DECL(_net_inet_esp);
83 SYSCTL_VNET_INT(_net_inet_esp, OID_AUTO,
84         esp_enable,     CTLFLAG_RW,     &VNET_NAME(esp_enable), 0, "");
85 SYSCTL_VNET_STRUCT(_net_inet_esp, IPSECCTL_STATS,
86         stats,          CTLFLAG_RD,     &VNET_NAME(espstat),    espstat, "");
87
88 static VNET_DEFINE(int, esp_max_ivlen); /* max iv length over all algorithms */
89 #define V_esp_max_ivlen VNET(esp_max_ivlen)
90
91 static int esp_input_cb(struct cryptop *op);
92 static int esp_output_cb(struct cryptop *crp);
93
94 /*
95  * NB: this is public for use by the PF_KEY support.
96  * NB: if you add support here; be sure to add code to esp_attach below!
97  */
98 struct enc_xform *
99 esp_algorithm_lookup(int alg)
100 {
101         if (alg >= ESP_ALG_MAX)
102                 return NULL;
103         switch (alg) {
104         case SADB_EALG_DESCBC:
105                 return &enc_xform_des;
106         case SADB_EALG_3DESCBC:
107                 return &enc_xform_3des;
108         case SADB_X_EALG_AES:
109                 return &enc_xform_rijndael128;
110         case SADB_X_EALG_BLOWFISHCBC:
111                 return &enc_xform_blf;
112         case SADB_X_EALG_CAST128CBC:
113                 return &enc_xform_cast5;
114         case SADB_X_EALG_SKIPJACK:
115                 return &enc_xform_skipjack;
116         case SADB_EALG_NULL:
117                 return &enc_xform_null;
118         case SADB_X_EALG_CAMELLIACBC:
119                 return &enc_xform_camellia;
120         }
121         return NULL;
122 }
123
124 size_t
125 esp_hdrsiz(struct secasvar *sav)
126 {
127         size_t size;
128
129         if (sav != NULL) {
130                 /*XXX not right for null algorithm--does it matter??*/
131                 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
132                         ("SA with null xform"));
133                 if (sav->flags & SADB_X_EXT_OLD)
134                         size = sizeof (struct esp);
135                 else
136                         size = sizeof (struct newesp);
137                 size += sav->tdb_encalgxform->blocksize + 9;
138                 /*XXX need alg check???*/
139                 if (sav->tdb_authalgxform != NULL && sav->replay)
140                         size += ah_hdrsiz(sav);
141         } else {
142                 /*
143                  *   base header size
144                  * + max iv length for CBC mode
145                  * + max pad length
146                  * + sizeof (pad length field)
147                  * + sizeof (next header field)
148                  * + max icv supported.
149                  */
150                 size = sizeof (struct newesp) + V_esp_max_ivlen + 9 + 16;
151         }
152         return size;
153 }
154
155 /*
156  * esp_init() is called when an SPI is being set up.
157  */
158 static int
159 esp_init(struct secasvar *sav, struct xformsw *xsp)
160 {
161         struct enc_xform *txform;
162         struct cryptoini cria, crie;
163         int keylen;
164         int error;
165
166         txform = esp_algorithm_lookup(sav->alg_enc);
167         if (txform == NULL) {
168                 DPRINTF(("%s: unsupported encryption algorithm %d\n",
169                         __func__, sav->alg_enc));
170                 return EINVAL;
171         }
172         if (sav->key_enc == NULL) {
173                 DPRINTF(("%s: no encoding key for %s algorithm\n",
174                          __func__, txform->name));
175                 return EINVAL;
176         }
177         if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
178                 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
179                         __func__));
180                 return EINVAL;
181         }
182         keylen = _KEYLEN(sav->key_enc);
183         if (txform->minkey > keylen || keylen > txform->maxkey) {
184                 DPRINTF(("%s: invalid key length %u, must be in the range "
185                         "[%u..%u] for algorithm %s\n", __func__,
186                         keylen, txform->minkey, txform->maxkey,
187                         txform->name));
188                 return EINVAL;
189         }
190
191         /*
192          * NB: The null xform needs a non-zero blocksize to keep the
193          *      crypto code happy but if we use it to set ivlen then
194          *      the ESP header will be processed incorrectly.  The
195          *      compromise is to force it to zero here.
196          */
197         sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
198         sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
199         if (sav->iv == NULL) {
200                 DPRINTF(("%s: no memory for IV\n", __func__));
201                 return EINVAL;
202         }
203         key_randomfill(sav->iv, sav->ivlen);    /*XXX*/
204
205         /*
206          * Setup AH-related state.
207          */
208         if (sav->alg_auth != 0) {
209                 error = ah_init0(sav, xsp, &cria);
210                 if (error)
211                         return error;
212         }
213
214         /* NB: override anything set in ah_init0 */
215         sav->tdb_xform = xsp;
216         sav->tdb_encalgxform = txform;
217
218         /* Initialize crypto session. */
219         bzero(&crie, sizeof (crie));
220         crie.cri_alg = sav->tdb_encalgxform->type;
221         crie.cri_klen = _KEYBITS(sav->key_enc);
222         crie.cri_key = sav->key_enc->key_data;
223         /* XXX Rounds ? */
224
225         if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
226                 /* init both auth & enc */
227                 crie.cri_next = &cria;
228                 error = crypto_newsession(&sav->tdb_cryptoid,
229                                           &crie, V_crypto_support);
230         } else if (sav->tdb_encalgxform) {
231                 error = crypto_newsession(&sav->tdb_cryptoid,
232                                           &crie, V_crypto_support);
233         } else if (sav->tdb_authalgxform) {
234                 error = crypto_newsession(&sav->tdb_cryptoid,
235                                           &cria, V_crypto_support);
236         } else {
237                 /* XXX cannot happen? */
238                 DPRINTF(("%s: no encoding OR authentication xform!\n",
239                         __func__));
240                 error = EINVAL;
241         }
242         return error;
243 }
244
245 /*
246  * Paranoia.
247  */
248 static int
249 esp_zeroize(struct secasvar *sav)
250 {
251         /* NB: ah_zerorize free's the crypto session state */
252         int error = ah_zeroize(sav);
253
254         if (sav->key_enc)
255                 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
256         if (sav->iv) {
257                 free(sav->iv, M_XDATA);
258                 sav->iv = NULL;
259         }
260         sav->tdb_encalgxform = NULL;
261         sav->tdb_xform = NULL;
262         return error;
263 }
264
265 /*
266  * ESP input processing, called (eventually) through the protocol switch.
267  */
268 static int
269 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
270 {
271         struct auth_hash *esph;
272         struct enc_xform *espx;
273         struct tdb_ident *tdbi;
274         struct tdb_crypto *tc;
275         int plen, alen, hlen;
276         struct m_tag *mtag;
277         struct newesp *esp;
278
279         struct cryptodesc *crde;
280         struct cryptop *crp;
281
282         IPSEC_ASSERT(sav != NULL, ("null SA"));
283         IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
284         IPSEC_ASSERT((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
285                 ("misaligned packet, skip %u pkt len %u",
286                         skip, m->m_pkthdr.len));
287
288         /* XXX don't pullup, just copy header */
289         IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
290
291         esph = sav->tdb_authalgxform;
292         espx = sav->tdb_encalgxform;
293
294         /* Determine the ESP header length */
295         if (sav->flags & SADB_X_EXT_OLD)
296                 hlen = sizeof (struct esp) + sav->ivlen;
297         else
298                 hlen = sizeof (struct newesp) + sav->ivlen;
299         /* Authenticator hash size */
300         if (esph != NULL) {
301                 switch (esph->type) {
302                 case CRYPTO_SHA2_256_HMAC:
303                 case CRYPTO_SHA2_384_HMAC:
304                 case CRYPTO_SHA2_512_HMAC:
305                         alen = esph->hashsize/2;
306                         break;
307                 default:
308                         alen = AH_HMAC_HASHLEN;
309                         break;
310                 }
311         }else
312                 alen = 0;
313
314         /*
315          * Verify payload length is multiple of encryption algorithm
316          * block size.
317          *
318          * NB: This works for the null algorithm because the blocksize
319          *     is 4 and all packets must be 4-byte aligned regardless
320          *     of the algorithm.
321          */
322         plen = m->m_pkthdr.len - (skip + hlen + alen);
323         if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
324                 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
325                     "  SA %s/%08lx\n", __func__,
326                     plen, espx->blocksize,
327                     ipsec_address(&sav->sah->saidx.dst),
328                     (u_long) ntohl(sav->spi)));
329                 V_espstat.esps_badilen++;
330                 m_freem(m);
331                 return EINVAL;
332         }
333
334         /*
335          * Check sequence number.
336          */
337         if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
338                 DPRINTF(("%s: packet replay check for %s\n", __func__,
339                     ipsec_logsastr(sav)));      /*XXX*/
340                 V_espstat.esps_replay++;
341                 m_freem(m);
342                 return ENOBUFS;         /*XXX*/
343         }
344
345         /* Update the counters */
346         V_espstat.esps_ibytes += m->m_pkthdr.len - (skip + hlen + alen);
347
348         /* Find out if we've already done crypto */
349         for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
350              mtag != NULL;
351              mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
352                 tdbi = (struct tdb_ident *) (mtag + 1);
353                 if (tdbi->proto == sav->sah->saidx.proto &&
354                     tdbi->spi == sav->spi &&
355                     !bcmp(&tdbi->dst, &sav->sah->saidx.dst,
356                           sizeof(union sockaddr_union)))
357                         break;
358         }
359
360         /* Get crypto descriptors */
361         crp = crypto_getreq(esph && espx ? 2 : 1);
362         if (crp == NULL) {
363                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
364                         __func__));
365                 V_espstat.esps_crypto++;
366                 m_freem(m);
367                 return ENOBUFS;
368         }
369
370         /* Get IPsec-specific opaque pointer */
371         if (esph == NULL || mtag != NULL)
372                 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
373                     M_XDATA, M_NOWAIT|M_ZERO);
374         else
375                 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
376                     M_XDATA, M_NOWAIT|M_ZERO);
377         if (tc == NULL) {
378                 crypto_freereq(crp);
379                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
380                 V_espstat.esps_crypto++;
381                 m_freem(m);
382                 return ENOBUFS;
383         }
384
385         tc->tc_ptr = (caddr_t) mtag;
386
387         if (esph) {
388                 struct cryptodesc *crda = crp->crp_desc;
389
390                 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
391
392                 /* Authentication descriptor */
393                 crda->crd_skip = skip;
394                 crda->crd_len = m->m_pkthdr.len - (skip + alen);
395                 crda->crd_inject = m->m_pkthdr.len - alen;
396
397                 crda->crd_alg = esph->type;
398                 crda->crd_key = sav->key_auth->key_data;
399                 crda->crd_klen = _KEYBITS(sav->key_auth);
400
401                 /* Copy the authenticator */
402                 if (mtag == NULL)
403                         m_copydata(m, m->m_pkthdr.len - alen, alen,
404                                    (caddr_t) (tc + 1));
405
406                 /* Chain authentication request */
407                 crde = crda->crd_next;
408         } else {
409                 crde = crp->crp_desc;
410         }
411
412         /* Crypto operation descriptor */
413         crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
414         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
415         crp->crp_buf = (caddr_t) m;
416         crp->crp_callback = esp_input_cb;
417         crp->crp_sid = sav->tdb_cryptoid;
418         crp->crp_opaque = (caddr_t) tc;
419
420         /* These are passed as-is to the callback */
421         tc->tc_spi = sav->spi;
422         tc->tc_dst = sav->sah->saidx.dst;
423         tc->tc_proto = sav->sah->saidx.proto;
424         tc->tc_protoff = protoff;
425         tc->tc_skip = skip;
426         KEY_ADDREFSA(sav);
427         tc->tc_sav = sav;
428
429         /* Decryption descriptor */
430         if (espx) {
431                 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
432                 crde->crd_skip = skip + hlen;
433                 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
434                 crde->crd_inject = skip + hlen - sav->ivlen;
435
436                 crde->crd_alg = espx->type;
437                 crde->crd_key = sav->key_enc->key_data;
438                 crde->crd_klen = _KEYBITS(sav->key_enc);
439                 /* XXX Rounds ? */
440         }
441
442         if (mtag == NULL)
443                 return crypto_dispatch(crp);
444         else
445                 return esp_input_cb(crp);
446 }
447
448 #ifdef INET6
449 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {              \
450         if (saidx->dst.sa.sa_family == AF_INET6) {                           \
451                 error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
452         } else {                                                             \
453                 error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
454         }                                                                    \
455 } while (0)
456 #else
457 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)                   \
458         (error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
459 #endif
460
461 /*
462  * ESP input callback from the crypto driver.
463  */
464 static int
465 esp_input_cb(struct cryptop *crp)
466 {
467         u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
468         int hlen, skip, protoff, error, alen;
469         struct mbuf *m;
470         struct cryptodesc *crd;
471         struct auth_hash *esph;
472         struct enc_xform *espx;
473         struct tdb_crypto *tc;
474         struct m_tag *mtag;
475         struct secasvar *sav;
476         struct secasindex *saidx;
477         caddr_t ptr;
478
479         crd = crp->crp_desc;
480         IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
481
482         tc = (struct tdb_crypto *) crp->crp_opaque;
483         IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
484         skip = tc->tc_skip;
485         protoff = tc->tc_protoff;
486         mtag = (struct m_tag *) tc->tc_ptr;
487         m = (struct mbuf *) crp->crp_buf;
488
489         sav = tc->tc_sav;
490         IPSEC_ASSERT(sav != NULL, ("null SA!"));
491
492         saidx = &sav->sah->saidx;
493         IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
494                 saidx->dst.sa.sa_family == AF_INET6,
495                 ("unexpected protocol family %u", saidx->dst.sa.sa_family));
496
497         esph = sav->tdb_authalgxform;
498         espx = sav->tdb_encalgxform;
499
500         /* Check for crypto errors */
501         if (crp->crp_etype) {
502                 /* Reset the session ID */
503                 if (sav->tdb_cryptoid != 0)
504                         sav->tdb_cryptoid = crp->crp_sid;
505
506                 if (crp->crp_etype == EAGAIN) {
507                         error = crypto_dispatch(crp);
508                         return error;
509                 }
510
511                 V_espstat.esps_noxform++;
512                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
513                 error = crp->crp_etype;
514                 goto bad;
515         }
516
517         /* Shouldn't happen... */
518         if (m == NULL) {
519                 V_espstat.esps_crypto++;
520                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
521                 error = EINVAL;
522                 goto bad;
523         }
524         V_espstat.esps_hist[sav->alg_enc]++;
525
526         /* If authentication was performed, check now. */
527         if (esph != NULL) {
528                 switch (esph->type) {
529                 case CRYPTO_SHA2_256_HMAC:
530                 case CRYPTO_SHA2_384_HMAC:
531                 case CRYPTO_SHA2_512_HMAC:
532                         alen = esph->hashsize/2;
533                         break;
534                 default:
535                         alen = AH_HMAC_HASHLEN;
536                         break;
537                 }
538                 /*
539                  * If we have a tag, it means an IPsec-aware NIC did
540                  * the verification for us.  Otherwise we need to
541                  * check the authentication calculation.
542                  */
543                 V_ahstat.ahs_hist[sav->alg_auth]++;
544                 if (mtag == NULL) {
545                         /* Copy the authenticator from the packet */
546                         m_copydata(m, m->m_pkthdr.len - alen,
547                                 alen, aalg);
548
549                         ptr = (caddr_t) (tc + 1);
550
551                         /* Verify authenticator */
552                         if (bcmp(ptr, aalg, alen) != 0) {
553                                 DPRINTF(("%s: "
554                     "authentication hash mismatch for packet in SA %s/%08lx\n",
555                                     __func__,
556                                     ipsec_address(&saidx->dst),
557                                     (u_long) ntohl(sav->spi)));
558                                 V_espstat.esps_badauth++;
559                                 error = EACCES;
560                                 goto bad;
561                         }
562                 }
563
564                 /* Remove trailing authenticator */
565                 m_adj(m, -alen);
566         }
567
568         /* Release the crypto descriptors */
569         free(tc, M_XDATA), tc = NULL;
570         crypto_freereq(crp), crp = NULL;
571
572         /*
573          * Packet is now decrypted.
574          */
575         m->m_flags |= M_DECRYPTED;
576
577         /*
578          * Update replay sequence number, if appropriate.
579          */
580         if (sav->replay) {
581                 u_int32_t seq;
582
583                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
584                            sizeof (seq), (caddr_t) &seq);
585                 if (ipsec_updatereplay(ntohl(seq), sav)) {
586                         DPRINTF(("%s: packet replay check for %s\n", __func__,
587                             ipsec_logsastr(sav)));
588                         V_espstat.esps_replay++;
589                         error = ENOBUFS;
590                         goto bad;
591                 }
592         }
593
594         /* Determine the ESP header length */
595         if (sav->flags & SADB_X_EXT_OLD)
596                 hlen = sizeof (struct esp) + sav->ivlen;
597         else
598                 hlen = sizeof (struct newesp) + sav->ivlen;
599
600         /* Remove the ESP header and IV from the mbuf. */
601         error = m_striphdr(m, skip, hlen);
602         if (error) {
603                 V_espstat.esps_hdrops++;
604                 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
605                     ipsec_address(&sav->sah->saidx.dst),
606                     (u_long) ntohl(sav->spi)));
607                 goto bad;
608         }
609
610         /* Save the last three bytes of decrypted data */
611         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
612
613         /* Verify pad length */
614         if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
615                 V_espstat.esps_badilen++;
616                 DPRINTF(("%s: invalid padding length %d for %u byte packet "
617                         "in SA %s/%08lx\n", __func__,
618                          lastthree[1], m->m_pkthdr.len - skip,
619                          ipsec_address(&sav->sah->saidx.dst),
620                          (u_long) ntohl(sav->spi)));
621                 error = EINVAL;
622                 goto bad;
623         }
624
625         /* Verify correct decryption by checking the last padding bytes */
626         if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
627                 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
628                         V_espstat.esps_badenc++;
629                         DPRINTF(("%s: decryption failed for packet in "
630                                 "SA %s/%08lx\n", __func__,
631                                 ipsec_address(&sav->sah->saidx.dst),
632                                 (u_long) ntohl(sav->spi)));
633                         error = EINVAL;
634                         goto bad;
635                 }
636         }
637
638         /* Trim the mbuf chain to remove trailing authenticator and padding */
639         m_adj(m, -(lastthree[1] + 2));
640
641         /* Restore the Next Protocol field */
642         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
643
644         IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
645
646         KEY_FREESAV(&sav);
647         return error;
648 bad:
649         if (sav)
650                 KEY_FREESAV(&sav);
651         if (m != NULL)
652                 m_freem(m);
653         if (tc != NULL)
654                 free(tc, M_XDATA);
655         if (crp != NULL)
656                 crypto_freereq(crp);
657         return error;
658 }
659
660 /*
661  * ESP output routine, called by ipsec[46]_process_packet().
662  */
663 static int
664 esp_output(
665         struct mbuf *m,
666         struct ipsecrequest *isr,
667         struct mbuf **mp,
668         int skip,
669         int protoff
670 )
671 {
672         struct enc_xform *espx;
673         struct auth_hash *esph;
674         int hlen, rlen, plen, padding, blks, alen, i, roff;
675         struct mbuf *mo = (struct mbuf *) NULL;
676         struct tdb_crypto *tc;
677         struct secasvar *sav;
678         struct secasindex *saidx;
679         unsigned char *pad;
680         u_int8_t prot;
681         int error, maxpacketsize;
682
683         struct cryptodesc *crde = NULL, *crda = NULL;
684         struct cryptop *crp;
685
686         sav = isr->sav;
687         IPSEC_ASSERT(sav != NULL, ("null SA"));
688         esph = sav->tdb_authalgxform;
689         espx = sav->tdb_encalgxform;
690         IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
691
692         if (sav->flags & SADB_X_EXT_OLD)
693                 hlen = sizeof (struct esp) + sav->ivlen;
694         else
695                 hlen = sizeof (struct newesp) + sav->ivlen;
696
697         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
698         /*
699          * NB: The null encoding transform has a blocksize of 4
700          *     so that headers are properly aligned.
701          */
702         blks = espx->blocksize;         /* IV blocksize */
703
704         /* XXX clamp padding length a la KAME??? */
705         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
706         plen = rlen + padding;          /* Padded payload length. */
707
708         if (esph)
709                 switch (esph->type) {
710                 case CRYPTO_SHA2_256_HMAC:
711                 case CRYPTO_SHA2_384_HMAC:
712                 case CRYPTO_SHA2_512_HMAC:
713                         alen = esph->hashsize/2;
714                         break;
715                 default:
716                 alen = AH_HMAC_HASHLEN;
717                         break;
718                 }
719         else
720                 alen = 0;
721
722         V_espstat.esps_output++;
723
724         saidx = &sav->sah->saidx;
725         /* Check for maximum packet size violations. */
726         switch (saidx->dst.sa.sa_family) {
727 #ifdef INET
728         case AF_INET:
729                 maxpacketsize = IP_MAXPACKET;
730                 break;
731 #endif /* INET */
732 #ifdef INET6
733         case AF_INET6:
734                 maxpacketsize = IPV6_MAXPACKET;
735                 break;
736 #endif /* INET6 */
737         default:
738                 DPRINTF(("%s: unknown/unsupported protocol "
739                     "family %d, SA %s/%08lx\n", __func__,
740                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
741                     (u_long) ntohl(sav->spi)));
742                 V_espstat.esps_nopf++;
743                 error = EPFNOSUPPORT;
744                 goto bad;
745         }
746         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
747                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
748                     "(len %u, max len %u)\n", __func__,
749                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
750                     skip + hlen + rlen + padding + alen, maxpacketsize));
751                 V_espstat.esps_toobig++;
752                 error = EMSGSIZE;
753                 goto bad;
754         }
755
756         /* Update the counters. */
757         V_espstat.esps_obytes += m->m_pkthdr.len - skip;
758
759         m = m_unshare(m, M_NOWAIT);
760         if (m == NULL) {
761                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
762                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
763                 V_espstat.esps_hdrops++;
764                 error = ENOBUFS;
765                 goto bad;
766         }
767
768         /* Inject ESP header. */
769         mo = m_makespace(m, skip, hlen, &roff);
770         if (mo == NULL) {
771                 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
772                     __func__, hlen, ipsec_address(&saidx->dst),
773                     (u_long) ntohl(sav->spi)));
774                 V_espstat.esps_hdrops++;                /* XXX diffs from openbsd */
775                 error = ENOBUFS;
776                 goto bad;
777         }
778
779         /* Initialize ESP header. */
780         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
781         if (sav->replay) {
782                 u_int32_t replay;
783
784 #ifdef REGRESSION
785                 /* Emulate replay attack when ipsec_replay is TRUE. */
786                 if (!V_ipsec_replay)
787 #endif
788                         sav->replay->count++;
789                 replay = htonl(sav->replay->count);
790                 bcopy((caddr_t) &replay,
791                     mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
792                     sizeof(u_int32_t));
793         }
794
795         /*
796          * Add padding -- better to do it ourselves than use the crypto engine,
797          * although if/when we support compression, we'd have to do that.
798          */
799         pad = (u_char *) m_pad(m, padding + alen);
800         if (pad == NULL) {
801                 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
802                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
803                 m = NULL;               /* NB: free'd by m_pad */
804                 error = ENOBUFS;
805                 goto bad;
806         }
807
808         /*
809          * Add padding: random, zero, or self-describing.
810          * XXX catch unexpected setting
811          */
812         switch (sav->flags & SADB_X_EXT_PMASK) {
813         case SADB_X_EXT_PRAND:
814                 (void) read_random(pad, padding - 2);
815                 break;
816         case SADB_X_EXT_PZERO:
817                 bzero(pad, padding - 2);
818                 break;
819         case SADB_X_EXT_PSEQ:
820                 for (i = 0; i < padding - 2; i++)
821                         pad[i] = i+1;
822                 break;
823         }
824
825         /* Fix padding length and Next Protocol in padding itself. */
826         pad[padding - 2] = padding - 2;
827         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
828
829         /* Fix Next Protocol in IPv4/IPv6 header. */
830         prot = IPPROTO_ESP;
831         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
832
833         /* Get crypto descriptors. */
834         crp = crypto_getreq(esph && espx ? 2 : 1);
835         if (crp == NULL) {
836                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
837                         __func__));
838                 V_espstat.esps_crypto++;
839                 error = ENOBUFS;
840                 goto bad;
841         }
842
843         if (espx) {
844                 crde = crp->crp_desc;
845                 crda = crde->crd_next;
846
847                 /* Encryption descriptor. */
848                 crde->crd_skip = skip + hlen;
849                 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
850                 crde->crd_flags = CRD_F_ENCRYPT;
851                 crde->crd_inject = skip + hlen - sav->ivlen;
852
853                 /* Encryption operation. */
854                 crde->crd_alg = espx->type;
855                 crde->crd_key = sav->key_enc->key_data;
856                 crde->crd_klen = _KEYBITS(sav->key_enc);
857                 /* XXX Rounds ? */
858         } else
859                 crda = crp->crp_desc;
860
861         /* IPsec-specific opaque crypto info. */
862         tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
863                 M_XDATA, M_NOWAIT|M_ZERO);
864         if (tc == NULL) {
865                 crypto_freereq(crp);
866                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
867                 V_espstat.esps_crypto++;
868                 error = ENOBUFS;
869                 goto bad;
870         }
871
872         /* Callback parameters */
873         tc->tc_isr = isr;
874         KEY_ADDREFSA(sav);
875         tc->tc_sav = sav;
876         tc->tc_spi = sav->spi;
877         tc->tc_dst = saidx->dst;
878         tc->tc_proto = saidx->proto;
879
880         /* Crypto operation descriptor. */
881         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
882         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
883         crp->crp_buf = (caddr_t) m;
884         crp->crp_callback = esp_output_cb;
885         crp->crp_opaque = (caddr_t) tc;
886         crp->crp_sid = sav->tdb_cryptoid;
887
888         if (esph) {
889                 /* Authentication descriptor. */
890                 crda->crd_skip = skip;
891                 crda->crd_len = m->m_pkthdr.len - (skip + alen);
892                 crda->crd_inject = m->m_pkthdr.len - alen;
893
894                 /* Authentication operation. */
895                 crda->crd_alg = esph->type;
896                 crda->crd_key = sav->key_auth->key_data;
897                 crda->crd_klen = _KEYBITS(sav->key_auth);
898         }
899
900         return crypto_dispatch(crp);
901 bad:
902         if (m)
903                 m_freem(m);
904         return (error);
905 }
906
907 /*
908  * ESP output callback from the crypto driver.
909  */
910 static int
911 esp_output_cb(struct cryptop *crp)
912 {
913         struct tdb_crypto *tc;
914         struct ipsecrequest *isr;
915         struct secasvar *sav;
916         struct mbuf *m;
917         int err, error;
918
919         tc = (struct tdb_crypto *) crp->crp_opaque;
920         IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
921         m = (struct mbuf *) crp->crp_buf;
922
923         isr = tc->tc_isr;
924         IPSECREQUEST_LOCK(isr);
925         sav = tc->tc_sav;
926         /* With the isr lock released SA pointer can be updated. */
927         if (sav != isr->sav) {
928                 V_espstat.esps_notdb++;
929                 DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
930                     __func__, ipsec_address(&tc->tc_dst),
931                     (u_long) ntohl(tc->tc_spi), tc->tc_proto));
932                 error = ENOBUFS;                /*XXX*/
933                 goto bad;
934         }
935
936         /* Check for crypto errors. */
937         if (crp->crp_etype) {
938                 /* Reset session ID. */
939                 if (sav->tdb_cryptoid != 0)
940                         sav->tdb_cryptoid = crp->crp_sid;
941
942                 if (crp->crp_etype == EAGAIN) {
943                         IPSECREQUEST_UNLOCK(isr);
944                         error = crypto_dispatch(crp);
945                         return error;
946                 }
947
948                 V_espstat.esps_noxform++;
949                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
950                 error = crp->crp_etype;
951                 goto bad;
952         }
953
954         /* Shouldn't happen... */
955         if (m == NULL) {
956                 V_espstat.esps_crypto++;
957                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
958                 error = EINVAL;
959                 goto bad;
960         }
961         V_espstat.esps_hist[sav->alg_enc]++;
962         if (sav->tdb_authalgxform != NULL)
963                 V_ahstat.ahs_hist[sav->alg_auth]++;
964
965         /* Release crypto descriptors. */
966         free(tc, M_XDATA);
967         crypto_freereq(crp);
968
969 #ifdef REGRESSION
970         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
971         if (V_ipsec_integrity) {
972                 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
973                 struct auth_hash *esph;
974
975                 /*
976                  * Corrupt HMAC if we want to test integrity verification of
977                  * the other side.
978                  */
979                 esph = sav->tdb_authalgxform;
980                 if (esph !=  NULL) {
981                         int alen;
982
983                         switch (esph->type) {
984                         case CRYPTO_SHA2_256_HMAC:
985                         case CRYPTO_SHA2_384_HMAC:
986                         case CRYPTO_SHA2_512_HMAC:
987                                 alen = esph->hashsize/2;
988                                 break;
989                         default:
990                                 alen = AH_HMAC_HASHLEN;
991                                 break;
992                         }
993                         m_copyback(m, m->m_pkthdr.len - alen,
994                             alen, ipseczeroes);
995                 }
996         }
997 #endif
998
999         /* NB: m is reclaimed by ipsec_process_done. */
1000         err = ipsec_process_done(m, isr);
1001         KEY_FREESAV(&sav);
1002         IPSECREQUEST_UNLOCK(isr);
1003         return err;
1004 bad:
1005         if (sav)
1006                 KEY_FREESAV(&sav);
1007         IPSECREQUEST_UNLOCK(isr);
1008         if (m)
1009                 m_freem(m);
1010         free(tc, M_XDATA);
1011         crypto_freereq(crp);
1012         return error;
1013 }
1014
1015 static struct xformsw esp_xformsw = {
1016         XF_ESP,         XFT_CONF|XFT_AUTH,      "IPsec ESP",
1017         esp_init,       esp_zeroize,            esp_input,
1018         esp_output
1019 };
1020
1021 static void
1022 esp_attach(void)
1023 {
1024 #define MAXIV(xform)                                    \
1025         if (xform.blocksize > V_esp_max_ivlen)          \
1026                 V_esp_max_ivlen = xform.blocksize       \
1027
1028         MAXIV(enc_xform_des);           /* SADB_EALG_DESCBC */
1029         MAXIV(enc_xform_3des);          /* SADB_EALG_3DESCBC */
1030         MAXIV(enc_xform_rijndael128);   /* SADB_X_EALG_AES */
1031         MAXIV(enc_xform_blf);           /* SADB_X_EALG_BLOWFISHCBC */
1032         MAXIV(enc_xform_cast5);         /* SADB_X_EALG_CAST128CBC */
1033         MAXIV(enc_xform_skipjack);      /* SADB_X_EALG_SKIPJACK */
1034         MAXIV(enc_xform_null);          /* SADB_EALG_NULL */
1035         MAXIV(enc_xform_camellia);      /* SADB_X_EALG_CAMELLIACBC */
1036
1037         xform_register(&esp_xformsw);
1038 #undef MAXIV
1039 }
1040 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);