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