]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/netipsec/xform_esp.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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         alen = esph ? AH_HMAC_HASHLEN : 0;
301
302         /*
303          * Verify payload length is multiple of encryption algorithm
304          * block size.
305          *
306          * NB: This works for the null algorithm because the blocksize
307          *     is 4 and all packets must be 4-byte aligned regardless
308          *     of the algorithm.
309          */
310         plen = m->m_pkthdr.len - (skip + hlen + alen);
311         if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
312                 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
313                     "  SA %s/%08lx\n", __func__,
314                     plen, espx->blocksize,
315                     ipsec_address(&sav->sah->saidx.dst),
316                     (u_long) ntohl(sav->spi)));
317                 V_espstat.esps_badilen++;
318                 m_freem(m);
319                 return EINVAL;
320         }
321
322         /*
323          * Check sequence number.
324          */
325         if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
326                 DPRINTF(("%s: packet replay check for %s\n", __func__,
327                     ipsec_logsastr(sav)));      /*XXX*/
328                 V_espstat.esps_replay++;
329                 m_freem(m);
330                 return ENOBUFS;         /*XXX*/
331         }
332
333         /* Update the counters */
334         V_espstat.esps_ibytes += m->m_pkthdr.len - (skip + hlen + alen);
335
336         /* Find out if we've already done crypto */
337         for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
338              mtag != NULL;
339              mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
340                 tdbi = (struct tdb_ident *) (mtag + 1);
341                 if (tdbi->proto == sav->sah->saidx.proto &&
342                     tdbi->spi == sav->spi &&
343                     !bcmp(&tdbi->dst, &sav->sah->saidx.dst,
344                           sizeof(union sockaddr_union)))
345                         break;
346         }
347
348         /* Get crypto descriptors */
349         crp = crypto_getreq(esph && espx ? 2 : 1);
350         if (crp == NULL) {
351                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
352                         __func__));
353                 V_espstat.esps_crypto++;
354                 m_freem(m);
355                 return ENOBUFS;
356         }
357
358         /* Get IPsec-specific opaque pointer */
359         if (esph == NULL || mtag != NULL)
360                 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
361                     M_XDATA, M_NOWAIT|M_ZERO);
362         else
363                 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
364                     M_XDATA, M_NOWAIT|M_ZERO);
365         if (tc == NULL) {
366                 crypto_freereq(crp);
367                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
368                 V_espstat.esps_crypto++;
369                 m_freem(m);
370                 return ENOBUFS;
371         }
372
373         tc->tc_ptr = (caddr_t) mtag;
374
375         if (esph) {
376                 struct cryptodesc *crda = crp->crp_desc;
377
378                 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
379
380                 /* Authentication descriptor */
381                 crda->crd_skip = skip;
382                 crda->crd_len = m->m_pkthdr.len - (skip + alen);
383                 crda->crd_inject = m->m_pkthdr.len - alen;
384
385                 crda->crd_alg = esph->type;
386                 crda->crd_key = sav->key_auth->key_data;
387                 crda->crd_klen = _KEYBITS(sav->key_auth);
388
389                 /* Copy the authenticator */
390                 if (mtag == NULL)
391                         m_copydata(m, m->m_pkthdr.len - alen, alen,
392                                    (caddr_t) (tc + 1));
393
394                 /* Chain authentication request */
395                 crde = crda->crd_next;
396         } else {
397                 crde = crp->crp_desc;
398         }
399
400         /* Crypto operation descriptor */
401         crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
402         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
403         crp->crp_buf = (caddr_t) m;
404         crp->crp_callback = esp_input_cb;
405         crp->crp_sid = sav->tdb_cryptoid;
406         crp->crp_opaque = (caddr_t) tc;
407
408         /* These are passed as-is to the callback */
409         tc->tc_spi = sav->spi;
410         tc->tc_dst = sav->sah->saidx.dst;
411         tc->tc_proto = sav->sah->saidx.proto;
412         tc->tc_protoff = protoff;
413         tc->tc_skip = skip;
414
415         /* Decryption descriptor */
416         if (espx) {
417                 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
418                 crde->crd_skip = skip + hlen;
419                 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
420                 crde->crd_inject = skip + hlen - sav->ivlen;
421
422                 crde->crd_alg = espx->type;
423                 crde->crd_key = sav->key_enc->key_data;
424                 crde->crd_klen = _KEYBITS(sav->key_enc);
425                 /* XXX Rounds ? */
426         }
427
428         if (mtag == NULL)
429                 return crypto_dispatch(crp);
430         else
431                 return esp_input_cb(crp);
432 }
433
434 #ifdef INET6
435 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {              \
436         if (saidx->dst.sa.sa_family == AF_INET6) {                           \
437                 error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
438         } else {                                                             \
439                 error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
440         }                                                                    \
441 } while (0)
442 #else
443 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)                   \
444         (error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
445 #endif
446
447 /*
448  * ESP input callback from the crypto driver.
449  */
450 static int
451 esp_input_cb(struct cryptop *crp)
452 {
453         u_int8_t lastthree[3], aalg[AH_HMAC_HASHLEN];
454         int hlen, skip, protoff, error;
455         struct mbuf *m;
456         struct cryptodesc *crd;
457         struct auth_hash *esph;
458         struct enc_xform *espx;
459         struct tdb_crypto *tc;
460         struct m_tag *mtag;
461         struct secasvar *sav;
462         struct secasindex *saidx;
463         caddr_t ptr;
464
465         crd = crp->crp_desc;
466         IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
467
468         tc = (struct tdb_crypto *) crp->crp_opaque;
469         IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
470         skip = tc->tc_skip;
471         protoff = tc->tc_protoff;
472         mtag = (struct m_tag *) tc->tc_ptr;
473         m = (struct mbuf *) crp->crp_buf;
474
475         sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
476         if (sav == NULL) {
477                 V_espstat.esps_notdb++;
478                 DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
479                     __func__, ipsec_address(&tc->tc_dst),
480                     (u_long) ntohl(tc->tc_spi), tc->tc_proto));
481                 error = ENOBUFS;                /*XXX*/
482                 goto bad;
483         }
484
485         saidx = &sav->sah->saidx;
486         IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
487                 saidx->dst.sa.sa_family == AF_INET6,
488                 ("unexpected protocol family %u", saidx->dst.sa.sa_family));
489
490         esph = sav->tdb_authalgxform;
491         espx = sav->tdb_encalgxform;
492
493         /* Check for crypto errors */
494         if (crp->crp_etype) {
495                 /* Reset the session ID */
496                 if (sav->tdb_cryptoid != 0)
497                         sav->tdb_cryptoid = crp->crp_sid;
498
499                 if (crp->crp_etype == EAGAIN) {
500                         KEY_FREESAV(&sav);
501                         error = crypto_dispatch(crp);
502                         return error;
503                 }
504
505                 V_espstat.esps_noxform++;
506                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
507                 error = crp->crp_etype;
508                 goto bad;
509         }
510
511         /* Shouldn't happen... */
512         if (m == NULL) {
513                 V_espstat.esps_crypto++;
514                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
515                 error = EINVAL;
516                 goto bad;
517         }
518         V_espstat.esps_hist[sav->alg_enc]++;
519
520         /* If authentication was performed, check now. */
521         if (esph != NULL) {
522                 /*
523                  * If we have a tag, it means an IPsec-aware NIC did
524                  * the verification for us.  Otherwise we need to
525                  * check the authentication calculation.
526                  */
527                 V_ahstat.ahs_hist[sav->alg_auth]++;
528                 if (mtag == NULL) {
529                         /* Copy the authenticator from the packet */
530                         m_copydata(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
531                                 AH_HMAC_HASHLEN, aalg);
532
533                         ptr = (caddr_t) (tc + 1);
534
535                         /* Verify authenticator */
536                         if (bcmp(ptr, aalg, AH_HMAC_HASHLEN) != 0) {
537                                 DPRINTF(("%s: "
538                     "authentication hash mismatch for packet in SA %s/%08lx\n",
539                                     __func__,
540                                     ipsec_address(&saidx->dst),
541                                     (u_long) ntohl(sav->spi)));
542                                 V_espstat.esps_badauth++;
543                                 error = EACCES;
544                                 goto bad;
545                         }
546                 }
547
548                 /* Remove trailing authenticator */
549                 m_adj(m, -AH_HMAC_HASHLEN);
550         }
551
552         /* Release the crypto descriptors */
553         free(tc, M_XDATA), tc = NULL;
554         crypto_freereq(crp), crp = NULL;
555
556         /*
557          * Packet is now decrypted.
558          */
559         m->m_flags |= M_DECRYPTED;
560
561         /*
562          * Update replay sequence number, if appropriate.
563          */
564         if (sav->replay) {
565                 u_int32_t seq;
566
567                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
568                            sizeof (seq), (caddr_t) &seq);
569                 if (ipsec_updatereplay(ntohl(seq), sav)) {
570                         DPRINTF(("%s: packet replay check for %s\n", __func__,
571                             ipsec_logsastr(sav)));
572                         V_espstat.esps_replay++;
573                         error = ENOBUFS;
574                         goto bad;
575                 }
576         }
577
578         /* Determine the ESP header length */
579         if (sav->flags & SADB_X_EXT_OLD)
580                 hlen = sizeof (struct esp) + sav->ivlen;
581         else
582                 hlen = sizeof (struct newesp) + sav->ivlen;
583
584         /* Remove the ESP header and IV from the mbuf. */
585         error = m_striphdr(m, skip, hlen);
586         if (error) {
587                 V_espstat.esps_hdrops++;
588                 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
589                     ipsec_address(&sav->sah->saidx.dst),
590                     (u_long) ntohl(sav->spi)));
591                 goto bad;
592         }
593
594         /* Save the last three bytes of decrypted data */
595         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
596
597         /* Verify pad length */
598         if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
599                 V_espstat.esps_badilen++;
600                 DPRINTF(("%s: invalid padding length %d for %u byte packet "
601                         "in SA %s/%08lx\n", __func__,
602                          lastthree[1], m->m_pkthdr.len - skip,
603                          ipsec_address(&sav->sah->saidx.dst),
604                          (u_long) ntohl(sav->spi)));
605                 error = EINVAL;
606                 goto bad;
607         }
608
609         /* Verify correct decryption by checking the last padding bytes */
610         if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
611                 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
612                         V_espstat.esps_badenc++;
613                         DPRINTF(("%s: decryption failed for packet in "
614                                 "SA %s/%08lx\n", __func__,
615                                 ipsec_address(&sav->sah->saidx.dst),
616                                 (u_long) ntohl(sav->spi)));
617                         error = EINVAL;
618                         goto bad;
619                 }
620         }
621
622         /* Trim the mbuf chain to remove trailing authenticator and padding */
623         m_adj(m, -(lastthree[1] + 2));
624
625         /* Restore the Next Protocol field */
626         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
627
628         IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
629
630         KEY_FREESAV(&sav);
631         return error;
632 bad:
633         if (sav)
634                 KEY_FREESAV(&sav);
635         if (m != NULL)
636                 m_freem(m);
637         if (tc != NULL)
638                 free(tc, M_XDATA);
639         if (crp != NULL)
640                 crypto_freereq(crp);
641         return error;
642 }
643
644 /*
645  * ESP output routine, called by ipsec[46]_process_packet().
646  */
647 static int
648 esp_output(
649         struct mbuf *m,
650         struct ipsecrequest *isr,
651         struct mbuf **mp,
652         int skip,
653         int protoff
654 )
655 {
656         struct enc_xform *espx;
657         struct auth_hash *esph;
658         int hlen, rlen, plen, padding, blks, alen, i, roff;
659         struct mbuf *mo = (struct mbuf *) NULL;
660         struct tdb_crypto *tc;
661         struct secasvar *sav;
662         struct secasindex *saidx;
663         unsigned char *pad;
664         u_int8_t prot;
665         int error, maxpacketsize;
666
667         struct cryptodesc *crde = NULL, *crda = NULL;
668         struct cryptop *crp;
669
670         sav = isr->sav;
671         IPSEC_ASSERT(sav != NULL, ("null SA"));
672         esph = sav->tdb_authalgxform;
673         espx = sav->tdb_encalgxform;
674         IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
675
676         if (sav->flags & SADB_X_EXT_OLD)
677                 hlen = sizeof (struct esp) + sav->ivlen;
678         else
679                 hlen = sizeof (struct newesp) + sav->ivlen;
680
681         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
682         /*
683          * NB: The null encoding transform has a blocksize of 4
684          *     so that headers are properly aligned.
685          */
686         blks = espx->blocksize;         /* IV blocksize */
687
688         /* XXX clamp padding length a la KAME??? */
689         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
690         plen = rlen + padding;          /* Padded payload length. */
691
692         if (esph)
693                 alen = AH_HMAC_HASHLEN;
694         else
695                 alen = 0;
696
697         V_espstat.esps_output++;
698
699         saidx = &sav->sah->saidx;
700         /* Check for maximum packet size violations. */
701         switch (saidx->dst.sa.sa_family) {
702 #ifdef INET
703         case AF_INET:
704                 maxpacketsize = IP_MAXPACKET;
705                 break;
706 #endif /* INET */
707 #ifdef INET6
708         case AF_INET6:
709                 maxpacketsize = IPV6_MAXPACKET;
710                 break;
711 #endif /* INET6 */
712         default:
713                 DPRINTF(("%s: unknown/unsupported protocol "
714                     "family %d, SA %s/%08lx\n", __func__,
715                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
716                     (u_long) ntohl(sav->spi)));
717                 V_espstat.esps_nopf++;
718                 error = EPFNOSUPPORT;
719                 goto bad;
720         }
721         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
722                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
723                     "(len %u, max len %u)\n", __func__,
724                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
725                     skip + hlen + rlen + padding + alen, maxpacketsize));
726                 V_espstat.esps_toobig++;
727                 error = EMSGSIZE;
728                 goto bad;
729         }
730
731         /* Update the counters. */
732         V_espstat.esps_obytes += m->m_pkthdr.len - skip;
733
734         m = m_unshare(m, M_NOWAIT);
735         if (m == NULL) {
736                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
737                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
738                 V_espstat.esps_hdrops++;
739                 error = ENOBUFS;
740                 goto bad;
741         }
742
743         /* Inject ESP header. */
744         mo = m_makespace(m, skip, hlen, &roff);
745         if (mo == NULL) {
746                 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
747                     __func__, hlen, ipsec_address(&saidx->dst),
748                     (u_long) ntohl(sav->spi)));
749                 V_espstat.esps_hdrops++;                /* XXX diffs from openbsd */
750                 error = ENOBUFS;
751                 goto bad;
752         }
753
754         /* Initialize ESP header. */
755         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
756         if (sav->replay) {
757                 u_int32_t replay;
758
759 #ifdef REGRESSION
760                 /* Emulate replay attack when ipsec_replay is TRUE. */
761                 if (!V_ipsec_replay)
762 #endif
763                         sav->replay->count++;
764                 replay = htonl(sav->replay->count);
765                 bcopy((caddr_t) &replay,
766                     mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
767                     sizeof(u_int32_t));
768         }
769
770         /*
771          * Add padding -- better to do it ourselves than use the crypto engine,
772          * although if/when we support compression, we'd have to do that.
773          */
774         pad = (u_char *) m_pad(m, padding + alen);
775         if (pad == NULL) {
776                 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
777                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
778                 m = NULL;               /* NB: free'd by m_pad */
779                 error = ENOBUFS;
780                 goto bad;
781         }
782
783         /*
784          * Add padding: random, zero, or self-describing.
785          * XXX catch unexpected setting
786          */
787         switch (sav->flags & SADB_X_EXT_PMASK) {
788         case SADB_X_EXT_PRAND:
789                 (void) read_random(pad, padding - 2);
790                 break;
791         case SADB_X_EXT_PZERO:
792                 bzero(pad, padding - 2);
793                 break;
794         case SADB_X_EXT_PSEQ:
795                 for (i = 0; i < padding - 2; i++)
796                         pad[i] = i+1;
797                 break;
798         }
799
800         /* Fix padding length and Next Protocol in padding itself. */
801         pad[padding - 2] = padding - 2;
802         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
803
804         /* Fix Next Protocol in IPv4/IPv6 header. */
805         prot = IPPROTO_ESP;
806         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
807
808         /* Get crypto descriptors. */
809         crp = crypto_getreq(esph && espx ? 2 : 1);
810         if (crp == NULL) {
811                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
812                         __func__));
813                 V_espstat.esps_crypto++;
814                 error = ENOBUFS;
815                 goto bad;
816         }
817
818         if (espx) {
819                 crde = crp->crp_desc;
820                 crda = crde->crd_next;
821
822                 /* Encryption descriptor. */
823                 crde->crd_skip = skip + hlen;
824                 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
825                 crde->crd_flags = CRD_F_ENCRYPT;
826                 crde->crd_inject = skip + hlen - sav->ivlen;
827
828                 /* Encryption operation. */
829                 crde->crd_alg = espx->type;
830                 crde->crd_key = sav->key_enc->key_data;
831                 crde->crd_klen = _KEYBITS(sav->key_enc);
832                 /* XXX Rounds ? */
833         } else
834                 crda = crp->crp_desc;
835
836         /* IPsec-specific opaque crypto info. */
837         tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
838                 M_XDATA, M_NOWAIT|M_ZERO);
839         if (tc == NULL) {
840                 crypto_freereq(crp);
841                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
842                 V_espstat.esps_crypto++;
843                 error = ENOBUFS;
844                 goto bad;
845         }
846
847         /* Callback parameters */
848         tc->tc_isr = isr;
849         tc->tc_spi = sav->spi;
850         tc->tc_dst = saidx->dst;
851         tc->tc_proto = saidx->proto;
852
853         /* Crypto operation descriptor. */
854         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
855         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
856         crp->crp_buf = (caddr_t) m;
857         crp->crp_callback = esp_output_cb;
858         crp->crp_opaque = (caddr_t) tc;
859         crp->crp_sid = sav->tdb_cryptoid;
860
861         if (esph) {
862                 /* Authentication descriptor. */
863                 crda->crd_skip = skip;
864                 crda->crd_len = m->m_pkthdr.len - (skip + alen);
865                 crda->crd_inject = m->m_pkthdr.len - alen;
866
867                 /* Authentication operation. */
868                 crda->crd_alg = esph->type;
869                 crda->crd_key = sav->key_auth->key_data;
870                 crda->crd_klen = _KEYBITS(sav->key_auth);
871         }
872
873         return crypto_dispatch(crp);
874 bad:
875         if (m)
876                 m_freem(m);
877         return (error);
878 }
879
880 /*
881  * ESP output callback from the crypto driver.
882  */
883 static int
884 esp_output_cb(struct cryptop *crp)
885 {
886         struct tdb_crypto *tc;
887         struct ipsecrequest *isr;
888         struct secasvar *sav;
889         struct mbuf *m;
890         int err, error;
891
892         tc = (struct tdb_crypto *) crp->crp_opaque;
893         IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
894         m = (struct mbuf *) crp->crp_buf;
895
896         isr = tc->tc_isr;
897         IPSECREQUEST_LOCK(isr);
898         sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
899         if (sav == NULL) {
900                 V_espstat.esps_notdb++;
901                 DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
902                     __func__, ipsec_address(&tc->tc_dst),
903                     (u_long) ntohl(tc->tc_spi), tc->tc_proto));
904                 error = ENOBUFS;                /*XXX*/
905                 goto bad;
906         }
907         IPSEC_ASSERT(isr->sav == sav,
908                 ("SA changed was %p now %p\n", isr->sav, sav));
909
910         /* Check for crypto errors. */
911         if (crp->crp_etype) {
912                 /* Reset session ID. */
913                 if (sav->tdb_cryptoid != 0)
914                         sav->tdb_cryptoid = crp->crp_sid;
915
916                 if (crp->crp_etype == EAGAIN) {
917                         KEY_FREESAV(&sav);
918                         IPSECREQUEST_UNLOCK(isr);
919                         error = crypto_dispatch(crp);
920                         return error;
921                 }
922
923                 V_espstat.esps_noxform++;
924                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
925                 error = crp->crp_etype;
926                 goto bad;
927         }
928
929         /* Shouldn't happen... */
930         if (m == NULL) {
931                 V_espstat.esps_crypto++;
932                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
933                 error = EINVAL;
934                 goto bad;
935         }
936         V_espstat.esps_hist[sav->alg_enc]++;
937         if (sav->tdb_authalgxform != NULL)
938                 V_ahstat.ahs_hist[sav->alg_auth]++;
939
940         /* Release crypto descriptors. */
941         free(tc, M_XDATA);
942         crypto_freereq(crp);
943
944 #ifdef REGRESSION
945         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
946         if (V_ipsec_integrity) {
947                 static unsigned char ipseczeroes[AH_HMAC_HASHLEN];
948                 struct auth_hash *esph;
949
950                 /*
951                  * Corrupt HMAC if we want to test integrity verification of
952                  * the other side.
953                  */
954                 esph = sav->tdb_authalgxform;
955                 if (esph !=  NULL) {
956                         m_copyback(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
957                             AH_HMAC_HASHLEN, ipseczeroes);
958                 }
959         }
960 #endif
961
962         /* NB: m is reclaimed by ipsec_process_done. */
963         err = ipsec_process_done(m, isr);
964         KEY_FREESAV(&sav);
965         IPSECREQUEST_UNLOCK(isr);
966         return err;
967 bad:
968         if (sav)
969                 KEY_FREESAV(&sav);
970         IPSECREQUEST_UNLOCK(isr);
971         if (m)
972                 m_freem(m);
973         free(tc, M_XDATA);
974         crypto_freereq(crp);
975         return error;
976 }
977
978 static struct xformsw esp_xformsw = {
979         XF_ESP,         XFT_CONF|XFT_AUTH,      "IPsec ESP",
980         esp_init,       esp_zeroize,            esp_input,
981         esp_output
982 };
983
984 static void
985 esp_attach(void)
986 {
987 #define MAXIV(xform)                                    \
988         if (xform.blocksize > V_esp_max_ivlen)          \
989                 V_esp_max_ivlen = xform.blocksize       \
990
991         MAXIV(enc_xform_des);           /* SADB_EALG_DESCBC */
992         MAXIV(enc_xform_3des);          /* SADB_EALG_3DESCBC */
993         MAXIV(enc_xform_rijndael128);   /* SADB_X_EALG_AES */
994         MAXIV(enc_xform_blf);           /* SADB_X_EALG_BLOWFISHCBC */
995         MAXIV(enc_xform_cast5);         /* SADB_X_EALG_CAST128CBC */
996         MAXIV(enc_xform_skipjack);      /* SADB_X_EALG_SKIPJACK */
997         MAXIV(enc_xform_null);          /* SADB_EALG_NULL */
998         MAXIV(enc_xform_camellia);      /* SADB_X_EALG_CAMELLIACBC */
999
1000         xform_register(&esp_xformsw);
1001 #undef MAXIV
1002 }
1003 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);