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