Sync our ieee80211*.9 manual pages with the recent upgrade.
[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.10 2006/03/22 19:57:32 drhodus 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         /*
557          * Update replay sequence number, if appropriate.
558          */
559         if (sav->replay) {
560                 u_int32_t seq;
561
562                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
563                            sizeof (seq), (caddr_t) &seq);
564                 if (ipsec_updatereplay(ntohl(seq), sav)) {
565                         DPRINTF(("%s: packet replay check for %s\n", __func__,
566                             ipsec_logsastr(sav)));
567                         espstat.esps_replay++;
568                         error = ENOBUFS;
569                         goto bad;
570                 }
571         }
572
573         /* Determine the ESP header length */
574         if (sav->flags & SADB_X_EXT_OLD)
575                 hlen = sizeof (struct esp) + sav->ivlen;
576         else
577                 hlen = sizeof (struct newesp) + sav->ivlen;
578
579         /* Remove the ESP header and IV from the mbuf. */
580         error = m_striphdr(m, skip, hlen);
581         if (error) {
582                 espstat.esps_hdrops++;
583                 DPRINTF(("esp_input_cb: bad mbuf chain, SA %s/%08lx\n",
584                     ipsec_address(&sav->sah->saidx.dst),
585                     (u_long) ntohl(sav->spi)));
586                 goto bad;
587         }
588
589         /* Save the last three bytes of decrypted data */
590         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
591
592         /* Verify pad length */
593         if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
594                 espstat.esps_badilen++;
595                 DPRINTF(("esp_input_cb: invalid padding length %d "
596                          "for %u byte packet in SA %s/%08lx\n",
597                          lastthree[1], m->m_pkthdr.len - skip,
598                          ipsec_address(&sav->sah->saidx.dst),
599                          (u_long) ntohl(sav->spi)));
600                 error = EINVAL;
601                 goto bad;
602         }
603
604         /* Verify correct decryption by checking the last padding bytes */
605         if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
606                 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
607                         espstat.esps_badenc++;
608                         DPRINTF(("esp_input_cb: decryption failed "
609                                 "for packet in SA %s/%08lx\n",
610                                 ipsec_address(&sav->sah->saidx.dst),
611                                 (u_long) ntohl(sav->spi)));
612 DPRINTF(("esp_input_cb: %x %x\n", lastthree[0], lastthree[1]));
613                         error = EINVAL;
614                         goto bad;
615                 }
616         }
617
618         /* Trim the mbuf chain to remove trailing authenticator and padding */
619         m_adj(m, -(lastthree[1] + 2));
620
621         /* Restore the Next Protocol field */
622         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
623
624         IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
625
626         KEY_FREESAV(&sav);
627         crit_exit();
628         return error;
629 bad:
630         if (sav)
631                 KEY_FREESAV(&sav);
632         crit_exit();
633         if (m != NULL)
634                 m_freem(m);
635         if (tc != NULL)
636                 free(tc, M_XDATA);
637         if (crp != NULL)
638                 crypto_freereq(crp);
639         return error;
640 }
641
642 /*
643  * ESP output routine, called by ipsec[46]_process_packet().
644  */
645 static int
646 esp_output(
647         struct mbuf *m,
648         struct ipsecrequest *isr,
649         struct mbuf **mp,
650         int skip,
651         int protoff
652 )
653 {
654         struct enc_xform *espx;
655         struct auth_hash *esph;
656         int hlen, rlen, plen, padding, blks, alen, i, roff;
657         struct mbuf *mo = (struct mbuf *) NULL;
658         struct tdb_crypto *tc;
659         struct secasvar *sav;
660         struct secasindex *saidx;
661         unsigned char *pad;
662         u_int8_t prot;
663         int error, maxpacketsize;
664
665         struct cryptodesc *crde = NULL, *crda = NULL;
666         struct cryptop *crp;
667
668         sav = isr->sav;
669         KASSERT(sav != NULL, ("esp_output: null SA"));
670         esph = sav->tdb_authalgxform;
671         espx = sav->tdb_encalgxform;
672         KASSERT(espx != NULL, ("esp_output: null encoding xform"));
673
674         if (sav->flags & SADB_X_EXT_OLD)
675                 hlen = sizeof (struct esp) + sav->ivlen;
676         else
677                 hlen = sizeof (struct newesp) + sav->ivlen;
678
679         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
680         /*
681          * NB: The null encoding transform has a blocksize of 4
682          *     so that headers are properly aligned.
683          */
684         blks = espx->blocksize;         /* IV blocksize */
685
686         /* XXX clamp padding length a la KAME??? */
687         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
688         plen = rlen + padding;          /* Padded payload length. */
689
690         if (esph)
691                 alen = AH_HMAC_HASHLEN;
692         else
693                 alen = 0;
694
695         espstat.esps_output++;
696
697         saidx = &sav->sah->saidx;
698         /* Check for maximum packet size violations. */
699         switch (saidx->dst.sa.sa_family) {
700 #ifdef INET
701         case AF_INET:
702                 maxpacketsize = IP_MAXPACKET;
703                 break;
704 #endif /* INET */
705 #ifdef INET6
706         case AF_INET6:
707                 maxpacketsize = IPV6_MAXPACKET;
708                 break;
709 #endif /* INET6 */
710         default:
711                 DPRINTF(("esp_output: unknown/unsupported protocol "
712                     "family %d, SA %s/%08lx\n",
713                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
714                     (u_long) ntohl(sav->spi)));
715                 espstat.esps_nopf++;
716                 error = EPFNOSUPPORT;
717                 goto bad;
718         }
719         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
720                 DPRINTF(("esp_output: packet in SA %s/%08lx got too big "
721                     "(len %u, max len %u)\n",
722                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
723                     skip + hlen + rlen + padding + alen, maxpacketsize));
724                 espstat.esps_toobig++;
725                 error = EMSGSIZE;
726                 goto bad;
727         }
728
729         /* Update the counters. */
730         espstat.esps_obytes += m->m_pkthdr.len - skip;
731
732         m = m_clone(m);
733         if (m == NULL) {
734                 DPRINTF(("esp_output: cannot clone mbuf chain, SA %s/%08lx\n",
735                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
736                 espstat.esps_hdrops++;
737                 error = ENOBUFS;
738                 goto bad;
739         }
740
741         /* Inject ESP header. */
742         mo = m_makespace(m, skip, hlen, &roff);
743         if (mo == NULL) {
744                 DPRINTF(("esp_output: failed to inject %u byte ESP hdr for SA "
745                     "%s/%08lx\n",
746                     hlen, ipsec_address(&saidx->dst),
747                     (u_long) ntohl(sav->spi)));
748                 espstat.esps_hdrops++;          /* XXX diffs from openbsd */
749                 error = ENOBUFS;
750                 goto bad;
751         }
752
753         /* Initialize ESP header. */
754         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
755         if (sav->replay) {
756                 u_int32_t replay = htonl(++(sav->replay->count));
757                 bcopy((caddr_t) &replay,
758                     mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
759                     sizeof(u_int32_t));
760         }
761
762         /*
763          * Add padding -- better to do it ourselves than use the crypto engine,
764          * although if/when we support compression, we'd have to do that.
765          */
766         pad = (u_char *) m_pad(m, padding + alen);
767         if (pad == NULL) {
768                 DPRINTF(("esp_output: m_pad failed for SA %s/%08lx\n",
769                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
770                 m = NULL;               /* NB: free'd by m_pad */
771                 error = ENOBUFS;
772                 goto bad;
773         }
774
775         /*
776          * Add padding: random, zero, or self-describing.
777          * XXX catch unexpected setting
778          */
779         switch (sav->flags & SADB_X_EXT_PMASK) {
780         case SADB_X_EXT_PRAND:
781                 read_random(pad, padding - 2);
782                 break;
783         case SADB_X_EXT_PZERO:
784                 bzero(pad, padding - 2);
785                 break;
786         case SADB_X_EXT_PSEQ:
787                 for (i = 0; i < padding - 2; i++)
788                         pad[i] = i+1;
789                 break;
790         }
791
792         /* Fix padding length and Next Protocol in padding itself. */
793         pad[padding - 2] = padding - 2;
794         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
795
796         /* Fix Next Protocol in IPv4/IPv6 header. */
797         prot = IPPROTO_ESP;
798         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
799
800         /* Get crypto descriptors. */
801         crp = crypto_getreq(esph && espx ? 2 : 1);
802         if (crp == NULL) {
803                 DPRINTF(("esp_output: failed to acquire crypto descriptors\n"));
804                 espstat.esps_crypto++;
805                 error = ENOBUFS;
806                 goto bad;
807         }
808
809         if (espx) {
810                 crde = crp->crp_desc;
811                 crda = crde->crd_next;
812
813                 /* Encryption descriptor. */
814                 crde->crd_skip = skip + hlen;
815                 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
816                 crde->crd_flags = CRD_F_ENCRYPT;
817                 crde->crd_inject = skip + hlen - sav->ivlen;
818
819                 /* Encryption operation. */
820                 crde->crd_alg = espx->type;
821                 crde->crd_key = _KEYBUF(sav->key_enc);
822                 crde->crd_klen = _KEYBITS(sav->key_enc);
823                 /* XXX Rounds ? */
824         } else
825                 crda = crp->crp_desc;
826
827         /* IPsec-specific opaque crypto info. */
828         tc = malloc(sizeof(struct tdb_crypto),
829                         M_XDATA, M_INTWAIT | M_ZERO | M_NULLOK);
830         if (tc == NULL) {
831                 crypto_freereq(crp);
832                 DPRINTF(("esp_output: failed to allocate tdb_crypto\n"));
833                 espstat.esps_crypto++;
834                 error = ENOBUFS;
835                 goto bad;
836         }
837
838         /* Callback parameters */
839         tc->tc_isr = isr;
840         tc->tc_spi = sav->spi;
841         tc->tc_dst = saidx->dst;
842         tc->tc_proto = saidx->proto;
843
844         /* Crypto operation descriptor. */
845         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
846         crp->crp_flags = CRYPTO_F_IMBUF;
847         crp->crp_buf = (caddr_t) m;
848         crp->crp_callback = esp_output_cb;
849         crp->crp_opaque = (caddr_t) tc;
850         crp->crp_sid = sav->tdb_cryptoid;
851
852         if (esph) {
853                 /* Authentication descriptor. */
854                 crda->crd_skip = skip;
855                 crda->crd_len = m->m_pkthdr.len - (skip + alen);
856                 crda->crd_inject = m->m_pkthdr.len - alen;
857
858                 /* Authentication operation. */
859                 crda->crd_alg = esph->type;
860                 crda->crd_key = _KEYBUF(sav->key_auth);
861                 crda->crd_klen = _KEYBITS(sav->key_auth);
862         }
863
864         return crypto_dispatch(crp);
865 bad:
866         if (m)
867                 m_freem(m);
868         return (error);
869 }
870
871 /*
872  * ESP output callback from the crypto driver.
873  */
874 static int
875 esp_output_cb(struct cryptop *crp)
876 {
877         struct tdb_crypto *tc;
878         struct ipsecrequest *isr;
879         struct secasvar *sav;
880         struct mbuf *m;
881         int err, error;
882
883         tc = (struct tdb_crypto *) crp->crp_opaque;
884         KASSERT(tc != NULL, ("esp_output_cb: null opaque data area!"));
885         m = (struct mbuf *) crp->crp_buf;
886
887         crit_enter();
888
889         isr = tc->tc_isr;
890         sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
891         if (sav == NULL) {
892                 espstat.esps_notdb++;
893                 DPRINTF(("esp_output_cb: SA expired while in crypto "
894                     "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
895                     (u_long) ntohl(tc->tc_spi), tc->tc_proto));
896                 error = ENOBUFS;                /*XXX*/
897                 goto bad;
898         }
899         KASSERT(isr->sav == sav,
900                 ("esp_output_cb: SA changed was %p now %p\n", isr->sav, sav));
901
902         /* Check for crypto errors. */
903         if (crp->crp_etype) {
904                 /* Reset session ID. */
905                 if (sav->tdb_cryptoid != 0)
906                         sav->tdb_cryptoid = crp->crp_sid;
907
908                 if (crp->crp_etype == EAGAIN) {
909                         KEY_FREESAV(&sav);
910                         crit_exit();
911                         return crypto_dispatch(crp);
912                 }
913
914                 espstat.esps_noxform++;
915                 DPRINTF(("esp_output_cb: crypto error %d\n", crp->crp_etype));
916                 error = crp->crp_etype;
917                 goto bad;
918         }
919
920         /* Shouldn't happen... */
921         if (m == NULL) {
922                 espstat.esps_crypto++;
923                 DPRINTF(("esp_output_cb: bogus returned buffer from crypto\n"));
924                 error = EINVAL;
925                 goto bad;
926         }
927         espstat.esps_hist[sav->alg_enc]++;
928         if (sav->tdb_authalgxform != NULL)
929                 ahstat.ahs_hist[sav->alg_auth]++;
930
931         /* Release crypto descriptors. */
932         free(tc, M_XDATA);
933         crypto_freereq(crp);
934
935         /* NB: m is reclaimed by ipsec_process_done. */
936         err = ipsec_process_done(m, isr);
937         KEY_FREESAV(&sav);
938         crit_exit();
939         return err;
940 bad:
941         if (sav)
942                 KEY_FREESAV(&sav);
943         crit_exit();
944         if (m)
945                 m_freem(m);
946         free(tc, M_XDATA);
947         crypto_freereq(crp);
948         return error;
949 }
950
951 static struct xformsw esp_xformsw = {
952         XF_ESP,         XFT_CONF|XFT_AUTH,      "IPsec ESP",
953         esp_init,       esp_zeroize,            esp_input,
954         esp_output
955 };
956
957 static void
958 esp_attach(void)
959 {
960 #define MAXIV(xform)                                    \
961         if (xform.blocksize > esp_max_ivlen)            \
962                 esp_max_ivlen = xform.blocksize         \
963
964         esp_max_ivlen = 0;
965         MAXIV(enc_xform_des);           /* SADB_EALG_DESCBC */
966         MAXIV(enc_xform_3des);          /* SADB_EALG_3DESCBC */
967         MAXIV(enc_xform_rijndael128);   /* SADB_X_EALG_AES */
968         MAXIV(enc_xform_blf);           /* SADB_X_EALG_BLOWFISHCBC */
969         MAXIV(enc_xform_cast5);         /* SADB_X_EALG_CAST128CBC */
970         MAXIV(enc_xform_skipjack);      /* SADB_X_EALG_SKIPJACK */
971         MAXIV(enc_xform_null);          /* SADB_EALG_NULL */
972
973         xform_register(&esp_xformsw);
974 #undef MAXIV
975 }
976 SYSINIT(esp_xform_init, SI_SUB_DRIVERS, SI_ORDER_FIRST, esp_attach, NULL)