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