]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netipsec/xform_ah.c
Merge the following revisions from ^/projects/release-vmimage:
[FreeBSD/FreeBSD.git] / sys / netipsec / xform_ah.c
1 /*      $FreeBSD$       */
2 /*      $OpenBSD: ip_ah.c,v 1.63 2001/06/26 06:18:58 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 and Niklas Hallqvist.
18  *
19  * Copyright (c) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20  * Angelos D. Keromytis and Niels Provos.
21  * Copyright (c) 1999 Niklas Hallqvist.
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/lock.h>
49 #include <sys/rwlock.h>
50 #include <sys/sysctl.h>
51
52 #include <net/if.h>
53 #include <net/vnet.h>
54
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_ecn.h>
59 #include <netinet/ip6.h>
60
61 #include <netipsec/ipsec.h>
62 #include <netipsec/ah.h>
63 #include <netipsec/ah_var.h>
64 #include <netipsec/xform.h>
65
66 #ifdef INET6
67 #include <netinet6/ip6_var.h>
68 #include <netipsec/ipsec6.h>
69 #include <netinet6/ip6_ecn.h>
70 #endif
71
72 #include <netipsec/key.h>
73 #include <netipsec/key_debug.h>
74
75 #include <opencrypto/cryptodev.h>
76
77 /*
78  * Return header size in bytes.  The old protocol did not support
79  * the replay counter; the new protocol always includes the counter.
80  */
81 #define HDRSIZE(sav) \
82         (((sav)->flags & SADB_X_EXT_OLD) ? \
83                 sizeof (struct ah) : sizeof (struct ah) + sizeof (u_int32_t))
84 /* 
85  * Return authenticator size in bytes.  The old protocol is known
86  * to use a fixed 16-byte authenticator.  The new algorithm use 12-byte
87  * authenticator.
88  */
89 #define AUTHSIZE(sav)   ah_authsize(sav)
90
91 VNET_DEFINE(int, ah_enable) = 1;        /* control flow of packets with AH */
92 VNET_DEFINE(int, ah_cleartos) = 1;      /* clear ip_tos when doing AH calc */
93 VNET_PCPUSTAT_DEFINE(struct ahstat, ahstat);
94 VNET_PCPUSTAT_SYSINIT(ahstat);
95
96 #ifdef VIMAGE
97 VNET_PCPUSTAT_SYSUNINIT(ahstat);
98 #endif /* VIMAGE */
99
100 #ifdef INET
101 SYSCTL_DECL(_net_inet_ah);
102 SYSCTL_INT(_net_inet_ah, OID_AUTO, ah_enable,
103         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_enable), 0, "");
104 SYSCTL_INT(_net_inet_ah, OID_AUTO, ah_cleartos,
105         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0, "");
106 SYSCTL_VNET_PCPUSTAT(_net_inet_ah, IPSECCTL_STATS, stats, struct ahstat,
107     ahstat, "AH statistics (struct ahstat, netipsec/ah_var.h)");
108 #endif
109
110 static unsigned char ipseczeroes[256];  /* larger than an ip6 extension hdr */
111
112 static int ah_input_cb(struct cryptop*);
113 static int ah_output_cb(struct cryptop*);
114
115 static int
116 ah_authsize(struct secasvar *sav)
117 {
118
119         IPSEC_ASSERT(sav != NULL, ("%s: sav == NULL", __func__));
120
121         if (sav->flags & SADB_X_EXT_OLD)
122                 return 16;
123
124         switch (sav->alg_auth) {
125         case SADB_X_AALG_SHA2_256:
126                 return 16;
127         case SADB_X_AALG_SHA2_384:
128                 return 24;
129         case SADB_X_AALG_SHA2_512:
130                 return 32;
131         default:
132                 return AH_HMAC_HASHLEN;
133         }
134         /* NOTREACHED */
135 }
136 /*
137  * NB: this is public for use by the PF_KEY support.
138  */
139 struct auth_hash *
140 ah_algorithm_lookup(int alg)
141 {
142         if (alg > SADB_AALG_MAX)
143                 return NULL;
144         switch (alg) {
145         case SADB_X_AALG_NULL:
146                 return &auth_hash_null;
147         case SADB_AALG_MD5HMAC:
148                 return &auth_hash_hmac_md5;
149         case SADB_AALG_SHA1HMAC:
150                 return &auth_hash_hmac_sha1;
151         case SADB_X_AALG_RIPEMD160HMAC:
152                 return &auth_hash_hmac_ripemd_160;
153         case SADB_X_AALG_MD5:
154                 return &auth_hash_key_md5;
155         case SADB_X_AALG_SHA:
156                 return &auth_hash_key_sha1;
157         case SADB_X_AALG_SHA2_256:
158                 return &auth_hash_hmac_sha2_256;
159         case SADB_X_AALG_SHA2_384:
160                 return &auth_hash_hmac_sha2_384;
161         case SADB_X_AALG_SHA2_512:
162                 return &auth_hash_hmac_sha2_512;
163         }
164         return NULL;
165 }
166
167 size_t
168 ah_hdrsiz(struct secasvar *sav)
169 {
170         size_t size;
171
172         if (sav != NULL) {
173                 int authsize;
174                 IPSEC_ASSERT(sav->tdb_authalgxform != NULL, ("null xform"));
175                 /*XXX not right for null algorithm--does it matter??*/
176                 authsize = AUTHSIZE(sav);
177                 size = roundup(authsize, sizeof (u_int32_t)) + HDRSIZE(sav);
178         } else {
179                 /* default guess */
180                 size = sizeof (struct ah) + sizeof (u_int32_t) + 16;
181         }
182         return size;
183 }
184
185 /*
186  * NB: public for use by esp_init.
187  */
188 int
189 ah_init0(struct secasvar *sav, struct xformsw *xsp, struct cryptoini *cria)
190 {
191         struct auth_hash *thash;
192         int keylen;
193
194         thash = ah_algorithm_lookup(sav->alg_auth);
195         if (thash == NULL) {
196                 DPRINTF(("%s: unsupported authentication algorithm %u\n",
197                         __func__, sav->alg_auth));
198                 return EINVAL;
199         }
200         /*
201          * Verify the replay state block allocation is consistent with
202          * the protocol type.  We check here so we can make assumptions
203          * later during protocol processing.
204          */
205         /* NB: replay state is setup elsewhere (sigh) */
206         if (((sav->flags&SADB_X_EXT_OLD) == 0) ^ (sav->replay != NULL)) {
207                 DPRINTF(("%s: replay state block inconsistency, "
208                         "%s algorithm %s replay state\n", __func__,
209                         (sav->flags & SADB_X_EXT_OLD) ? "old" : "new",
210                         sav->replay == NULL ? "without" : "with"));
211                 return EINVAL;
212         }
213         if (sav->key_auth == NULL) {
214                 DPRINTF(("%s: no authentication key for %s algorithm\n",
215                         __func__, thash->name));
216                 return EINVAL;
217         }
218         keylen = _KEYLEN(sav->key_auth);
219         if (keylen != thash->keysize && thash->keysize != 0) {
220                 DPRINTF(("%s: invalid keylength %d, algorithm %s requires "
221                         "keysize %d\n", __func__,
222                          keylen, thash->name, thash->keysize));
223                 return EINVAL;
224         }
225
226         sav->tdb_xform = xsp;
227         sav->tdb_authalgxform = thash;
228
229         /* Initialize crypto session. */
230         bzero(cria, sizeof (*cria));
231         cria->cri_alg = sav->tdb_authalgxform->type;
232         cria->cri_klen = _KEYBITS(sav->key_auth);
233         cria->cri_key = sav->key_auth->key_data;
234         cria->cri_mlen = AUTHSIZE(sav);
235
236         return 0;
237 }
238
239 /*
240  * ah_init() is called when an SPI is being set up.
241  */
242 static int
243 ah_init(struct secasvar *sav, struct xformsw *xsp)
244 {
245         struct cryptoini cria;
246         int error;
247
248         error = ah_init0(sav, xsp, &cria);
249         return error ? error :
250                  crypto_newsession(&sav->tdb_cryptoid, &cria, V_crypto_support);
251 }
252
253 /*
254  * Paranoia.
255  *
256  * NB: public for use by esp_zeroize (XXX).
257  */
258 int
259 ah_zeroize(struct secasvar *sav)
260 {
261         int err;
262
263         if (sav->key_auth)
264                 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
265
266         err = crypto_freesession(sav->tdb_cryptoid);
267         sav->tdb_cryptoid = 0;
268         sav->tdb_authalgxform = NULL;
269         sav->tdb_xform = NULL;
270         return err;
271 }
272
273 /*
274  * Massage IPv4/IPv6 headers for AH processing.
275  */
276 static int
277 ah_massage_headers(struct mbuf **m0, int proto, int skip, int alg, int out)
278 {
279         struct mbuf *m = *m0;
280         unsigned char *ptr;
281         int off, count;
282
283 #ifdef INET
284         struct ip *ip;
285 #endif /* INET */
286
287 #ifdef INET6
288         struct ip6_ext *ip6e;
289         struct ip6_hdr ip6;
290         int alloc, len, ad;
291 #endif /* INET6 */
292
293         switch (proto) {
294 #ifdef INET
295         case AF_INET:
296                 /*
297                  * This is the least painful way of dealing with IPv4 header
298                  * and option processing -- just make sure they're in
299                  * contiguous memory.
300                  */
301                 *m0 = m = m_pullup(m, skip);
302                 if (m == NULL) {
303                         DPRINTF(("%s: m_pullup failed\n", __func__));
304                         return ENOBUFS;
305                 }
306
307                 /* Fix the IP header */
308                 ip = mtod(m, struct ip *);
309                 if (V_ah_cleartos)
310                         ip->ip_tos = 0;
311                 ip->ip_ttl = 0;
312                 ip->ip_sum = 0;
313
314                 if (alg == CRYPTO_MD5_KPDK || alg == CRYPTO_SHA1_KPDK)
315                         ip->ip_off &= htons(IP_DF);
316                 else
317                         ip->ip_off = htons(0);
318
319                 ptr = mtod(m, unsigned char *) + sizeof(struct ip);
320
321                 /* IPv4 option processing */
322                 for (off = sizeof(struct ip); off < skip;) {
323                         if (ptr[off] == IPOPT_EOL || ptr[off] == IPOPT_NOP ||
324                             off + 1 < skip)
325                                 ;
326                         else {
327                                 DPRINTF(("%s: illegal IPv4 option length for "
328                                         "option %d\n", __func__, ptr[off]));
329
330                                 m_freem(m);
331                                 return EINVAL;
332                         }
333
334                         switch (ptr[off]) {
335                         case IPOPT_EOL:
336                                 off = skip;  /* End the loop. */
337                                 break;
338
339                         case IPOPT_NOP:
340                                 off++;
341                                 break;
342
343                         case IPOPT_SECURITY:    /* 0x82 */
344                         case 0x85:      /* Extended security. */
345                         case 0x86:      /* Commercial security. */
346                         case 0x94:      /* Router alert */
347                         case 0x95:      /* RFC1770 */
348                                 /* Sanity check for option length. */
349                                 if (ptr[off + 1] < 2) {
350                                         DPRINTF(("%s: illegal IPv4 option "
351                                                 "length for option %d\n",
352                                                 __func__, ptr[off]));
353
354                                         m_freem(m);
355                                         return EINVAL;
356                                 }
357
358                                 off += ptr[off + 1];
359                                 break;
360
361                         case IPOPT_LSRR:
362                         case IPOPT_SSRR:
363                                 /* Sanity check for option length. */
364                                 if (ptr[off + 1] < 2) {
365                                         DPRINTF(("%s: illegal IPv4 option "
366                                                 "length for option %d\n",
367                                                 __func__, ptr[off]));
368
369                                         m_freem(m);
370                                         return EINVAL;
371                                 }
372
373                                 /*
374                                  * On output, if we have either of the
375                                  * source routing options, we should
376                                  * swap the destination address of the
377                                  * IP header with the last address
378                                  * specified in the option, as that is
379                                  * what the destination's IP header
380                                  * will look like.
381                                  */
382                                 if (out)
383                                         bcopy(ptr + off + ptr[off + 1] -
384                                             sizeof(struct in_addr),
385                                             &(ip->ip_dst), sizeof(struct in_addr));
386
387                                 /* Fall through */
388                         default:
389                                 /* Sanity check for option length. */
390                                 if (ptr[off + 1] < 2) {
391                                         DPRINTF(("%s: illegal IPv4 option "
392                                                 "length for option %d\n",
393                                                 __func__, ptr[off]));
394                                         m_freem(m);
395                                         return EINVAL;
396                                 }
397
398                                 /* Zeroize all other options. */
399                                 count = ptr[off + 1];
400                                 bcopy(ipseczeroes, ptr, count);
401                                 off += count;
402                                 break;
403                         }
404
405                         /* Sanity check. */
406                         if (off > skip) {
407                                 DPRINTF(("%s: malformed IPv4 options header\n",
408                                         __func__));
409
410                                 m_freem(m);
411                                 return EINVAL;
412                         }
413                 }
414
415                 break;
416 #endif /* INET */
417
418 #ifdef INET6
419         case AF_INET6:  /* Ugly... */
420                 /* Copy and "cook" the IPv6 header. */
421                 m_copydata(m, 0, sizeof(ip6), (caddr_t) &ip6);
422
423                 /* We don't do IPv6 Jumbograms. */
424                 if (ip6.ip6_plen == 0) {
425                         DPRINTF(("%s: unsupported IPv6 jumbogram\n", __func__));
426                         m_freem(m);
427                         return EMSGSIZE;
428                 }
429
430                 ip6.ip6_flow = 0;
431                 ip6.ip6_hlim = 0;
432                 ip6.ip6_vfc &= ~IPV6_VERSION_MASK;
433                 ip6.ip6_vfc |= IPV6_VERSION;
434
435                 /* Scoped address handling. */
436                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_src))
437                         ip6.ip6_src.s6_addr16[1] = 0;
438                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6.ip6_dst))
439                         ip6.ip6_dst.s6_addr16[1] = 0;
440
441                 /* Done with IPv6 header. */
442                 m_copyback(m, 0, sizeof(struct ip6_hdr), (caddr_t) &ip6);
443
444                 /* Let's deal with the remaining headers (if any). */
445                 if (skip - sizeof(struct ip6_hdr) > 0) {
446                         if (m->m_len <= skip) {
447                                 ptr = (unsigned char *) malloc(
448                                     skip - sizeof(struct ip6_hdr),
449                                     M_XDATA, M_NOWAIT);
450                                 if (ptr == NULL) {
451                                         DPRINTF(("%s: failed to allocate memory"
452                                                 "for IPv6 headers\n",__func__));
453                                         m_freem(m);
454                                         return ENOBUFS;
455                                 }
456
457                                 /*
458                                  * Copy all the protocol headers after
459                                  * the IPv6 header.
460                                  */
461                                 m_copydata(m, sizeof(struct ip6_hdr),
462                                     skip - sizeof(struct ip6_hdr), ptr);
463                                 alloc = 1;
464                         } else {
465                                 /* No need to allocate memory. */
466                                 ptr = mtod(m, unsigned char *) +
467                                     sizeof(struct ip6_hdr);
468                                 alloc = 0;
469                         }
470                 } else
471                         break;
472
473                 off = ip6.ip6_nxt & 0xff; /* Next header type. */
474
475                 for (len = 0; len < skip - sizeof(struct ip6_hdr);)
476                         switch (off) {
477                         case IPPROTO_HOPOPTS:
478                         case IPPROTO_DSTOPTS:
479                                 ip6e = (struct ip6_ext *) (ptr + len);
480
481                                 /*
482                                  * Process the mutable/immutable
483                                  * options -- borrows heavily from the
484                                  * KAME code.
485                                  */
486                                 for (count = len + sizeof(struct ip6_ext);
487                                      count < len + ((ip6e->ip6e_len + 1) << 3);) {
488                                         if (ptr[count] == IP6OPT_PAD1) {
489                                                 count++;
490                                                 continue; /* Skip padding. */
491                                         }
492
493                                         /* Sanity check. */
494                                         if (count > len +
495                                             ((ip6e->ip6e_len + 1) << 3)) {
496                                                 m_freem(m);
497
498                                                 /* Free, if we allocated. */
499                                                 if (alloc)
500                                                         free(ptr, M_XDATA);
501                                                 return EINVAL;
502                                         }
503
504                                         ad = ptr[count + 1];
505
506                                         /* If mutable option, zeroize. */
507                                         if (ptr[count] & IP6OPT_MUTABLE)
508                                                 bcopy(ipseczeroes, ptr + count,
509                                                     ptr[count + 1]);
510
511                                         count += ad;
512
513                                         /* Sanity check. */
514                                         if (count >
515                                             skip - sizeof(struct ip6_hdr)) {
516                                                 m_freem(m);
517
518                                                 /* Free, if we allocated. */
519                                                 if (alloc)
520                                                         free(ptr, M_XDATA);
521                                                 return EINVAL;
522                                         }
523                                 }
524
525                                 /* Advance. */
526                                 len += ((ip6e->ip6e_len + 1) << 3);
527                                 off = ip6e->ip6e_nxt;
528                                 break;
529
530                         case IPPROTO_ROUTING:
531                                 /*
532                                  * Always include routing headers in
533                                  * computation.
534                                  */
535                                 ip6e = (struct ip6_ext *) (ptr + len);
536                                 len += ((ip6e->ip6e_len + 1) << 3);
537                                 off = ip6e->ip6e_nxt;
538                                 break;
539
540                         default:
541                                 DPRINTF(("%s: unexpected IPv6 header type %d",
542                                         __func__, off));
543                                 if (alloc)
544                                         free(ptr, M_XDATA);
545                                 m_freem(m);
546                                 return EINVAL;
547                         }
548
549                 /* Copyback and free, if we allocated. */
550                 if (alloc) {
551                         m_copyback(m, sizeof(struct ip6_hdr),
552                             skip - sizeof(struct ip6_hdr), ptr);
553                         free(ptr, M_XDATA);
554                 }
555
556                 break;
557 #endif /* INET6 */
558         }
559
560         return 0;
561 }
562
563 /*
564  * ah_input() gets called to verify that an input packet
565  * passes authentication.
566  */
567 static int
568 ah_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
569 {
570         struct auth_hash *ahx;
571         struct tdb_crypto *tc;
572         struct newah *ah;
573         int hl, rplen, authsize, error;
574
575         struct cryptodesc *crda;
576         struct cryptop *crp;
577
578         IPSEC_ASSERT(sav != NULL, ("null SA"));
579         IPSEC_ASSERT(sav->key_auth != NULL, ("null authentication key"));
580         IPSEC_ASSERT(sav->tdb_authalgxform != NULL,
581                 ("null authentication xform"));
582
583         /* Figure out header size. */
584         rplen = HDRSIZE(sav);
585
586         /* XXX don't pullup, just copy header */
587         IP6_EXTHDR_GET(ah, struct newah *, m, skip, rplen);
588         if (ah == NULL) {
589                 DPRINTF(("ah_input: cannot pullup header\n"));
590                 AHSTAT_INC(ahs_hdrops);         /*XXX*/
591                 m_freem(m);
592                 return ENOBUFS;
593         }
594
595         /* Check replay window, if applicable. */
596         if (sav->replay && !ipsec_chkreplay(ntohl(ah->ah_seq), sav)) {
597                 AHSTAT_INC(ahs_replay);
598                 DPRINTF(("%s: packet replay failure: %s\n", __func__,
599                           ipsec_logsastr(sav)));
600                 m_freem(m);
601                 return ENOBUFS;
602         }
603
604         /* Verify AH header length. */
605         hl = ah->ah_len * sizeof (u_int32_t);
606         ahx = sav->tdb_authalgxform;
607         authsize = AUTHSIZE(sav);
608         if (hl != authsize + rplen - sizeof (struct ah)) {
609                 DPRINTF(("%s: bad authenticator length %u (expecting %lu)"
610                         " for packet in SA %s/%08lx\n", __func__,
611                         hl, (u_long) (authsize + rplen - sizeof (struct ah)),
612                         ipsec_address(&sav->sah->saidx.dst),
613                         (u_long) ntohl(sav->spi)));
614                 AHSTAT_INC(ahs_badauthl);
615                 m_freem(m);
616                 return EACCES;
617         }
618         AHSTAT_ADD(ahs_ibytes, m->m_pkthdr.len - skip - hl);
619
620         /* Get crypto descriptors. */
621         crp = crypto_getreq(1);
622         if (crp == NULL) {
623                 DPRINTF(("%s: failed to acquire crypto descriptor\n",__func__));
624                 AHSTAT_INC(ahs_crypto);
625                 m_freem(m);
626                 return ENOBUFS;
627         }
628
629         crda = crp->crp_desc;
630         IPSEC_ASSERT(crda != NULL, ("null crypto descriptor"));
631
632         crda->crd_skip = 0;
633         crda->crd_len = m->m_pkthdr.len;
634         crda->crd_inject = skip + rplen;
635
636         /* Authentication operation. */
637         crda->crd_alg = ahx->type;
638         crda->crd_klen = _KEYBITS(sav->key_auth);
639         crda->crd_key = sav->key_auth->key_data;
640
641         /* Allocate IPsec-specific opaque crypto info. */
642         tc = (struct tdb_crypto *) malloc(sizeof (struct tdb_crypto) +
643             skip + rplen + authsize, M_XDATA, M_NOWAIT | M_ZERO);
644         if (tc == NULL) {
645                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
646                 AHSTAT_INC(ahs_crypto);
647                 crypto_freereq(crp);
648                 m_freem(m);
649                 return ENOBUFS;
650         }
651
652         /*
653          * Save the authenticator, the skipped portion of the packet,
654          * and the AH header.
655          */
656         m_copydata(m, 0, skip + rplen + authsize, (caddr_t)(tc+1));
657
658         /* Zeroize the authenticator on the packet. */
659         m_copyback(m, skip + rplen, authsize, ipseczeroes);
660
661         /* "Massage" the packet headers for crypto processing. */
662         error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
663             skip, ahx->type, 0);
664         if (error != 0) {
665                 /* NB: mbuf is free'd by ah_massage_headers */
666                 AHSTAT_INC(ahs_hdrops);
667                 free(tc, M_XDATA);
668                 crypto_freereq(crp);
669                 return (error);
670         }
671
672         /* Crypto operation descriptor. */
673         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
674         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
675         crp->crp_buf = (caddr_t) m;
676         crp->crp_callback = ah_input_cb;
677         crp->crp_sid = sav->tdb_cryptoid;
678         crp->crp_opaque = (caddr_t) tc;
679
680         /* These are passed as-is to the callback. */
681         tc->tc_spi = sav->spi;
682         tc->tc_dst = sav->sah->saidx.dst;
683         tc->tc_proto = sav->sah->saidx.proto;
684         tc->tc_nxt = ah->ah_nxt;
685         tc->tc_protoff = protoff;
686         tc->tc_skip = skip;
687         KEY_ADDREFSA(sav);
688         tc->tc_sav = sav;
689         return (crypto_dispatch(crp));
690 }
691
692 /*
693  * AH input callback from the crypto driver.
694  */
695 static int
696 ah_input_cb(struct cryptop *crp)
697 {
698         int rplen, error, skip, protoff;
699         unsigned char calc[AH_ALEN_MAX];
700         struct mbuf *m;
701         struct cryptodesc *crd;
702         struct auth_hash *ahx;
703         struct tdb_crypto *tc;
704         struct secasvar *sav;
705         struct secasindex *saidx;
706         u_int8_t nxt;
707         caddr_t ptr;
708         int authsize;
709
710         crd = crp->crp_desc;
711
712         tc = (struct tdb_crypto *) crp->crp_opaque;
713         IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
714         skip = tc->tc_skip;
715         nxt = tc->tc_nxt;
716         protoff = tc->tc_protoff;
717         m = (struct mbuf *) crp->crp_buf;
718
719         sav = tc->tc_sav;
720         IPSEC_ASSERT(sav != NULL, ("null SA!"));
721
722         saidx = &sav->sah->saidx;
723         IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
724                 saidx->dst.sa.sa_family == AF_INET6,
725                 ("unexpected protocol family %u", saidx->dst.sa.sa_family));
726
727         ahx = (struct auth_hash *) sav->tdb_authalgxform;
728
729         /* Check for crypto errors. */
730         if (crp->crp_etype) {
731                 if (sav->tdb_cryptoid != 0)
732                         sav->tdb_cryptoid = crp->crp_sid;
733
734                 if (crp->crp_etype == EAGAIN)
735                         return (crypto_dispatch(crp));
736
737                 AHSTAT_INC(ahs_noxform);
738                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
739                 error = crp->crp_etype;
740                 goto bad;
741         } else {
742                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
743                 crypto_freereq(crp);            /* No longer needed. */
744                 crp = NULL;
745         }
746
747         /* Shouldn't happen... */
748         if (m == NULL) {
749                 AHSTAT_INC(ahs_crypto);
750                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
751                 error = EINVAL;
752                 goto bad;
753         }
754
755         /* Figure out header size. */
756         rplen = HDRSIZE(sav);
757         authsize = AUTHSIZE(sav);
758
759         /* Copy authenticator off the packet. */
760         m_copydata(m, skip + rplen, authsize, calc);
761
762         /* Verify authenticator. */
763         ptr = (caddr_t) (tc + 1);
764         if (bcmp(ptr + skip + rplen, calc, authsize)) {
765                 DPRINTF(("%s: authentication hash mismatch for packet "
766                     "in SA %s/%08lx\n", __func__,
767                     ipsec_address(&saidx->dst),
768                     (u_long) ntohl(sav->spi)));
769                 AHSTAT_INC(ahs_badauth);
770                 error = EACCES;
771                 goto bad;
772         }
773         /* Fix the Next Protocol field. */
774         ((u_int8_t *) ptr)[protoff] = nxt;
775
776         /* Copyback the saved (uncooked) network headers. */
777         m_copyback(m, 0, skip, ptr);
778         free(tc, M_XDATA), tc = NULL;                   /* No longer needed */
779
780         /*
781          * Header is now authenticated.
782          */
783         m->m_flags |= M_AUTHIPHDR|M_AUTHIPDGM;
784
785         /*
786          * Update replay sequence number, if appropriate.
787          */
788         if (sav->replay) {
789                 u_int32_t seq;
790
791                 m_copydata(m, skip + offsetof(struct newah, ah_seq),
792                            sizeof (seq), (caddr_t) &seq);
793                 if (ipsec_updatereplay(ntohl(seq), sav)) {
794                         AHSTAT_INC(ahs_replay);
795                         error = ENOBUFS;                        /*XXX as above*/
796                         goto bad;
797                 }
798         }
799
800         /*
801          * Remove the AH header and authenticator from the mbuf.
802          */
803         error = m_striphdr(m, skip, rplen + authsize);
804         if (error) {
805                 DPRINTF(("%s: mangled mbuf chain for SA %s/%08lx\n", __func__,
806                     ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
807
808                 AHSTAT_INC(ahs_hdrops);
809                 goto bad;
810         }
811
812         switch (saidx->dst.sa.sa_family) {
813 #ifdef INET6
814         case AF_INET6:
815                 error = ipsec6_common_input_cb(m, sav, skip, protoff);
816                 break;
817 #endif
818 #ifdef INET
819         case AF_INET:
820                 error = ipsec4_common_input_cb(m, sav, skip, protoff);
821                 break;
822 #endif
823         default:
824                 panic("%s: Unexpected address family: %d saidx=%p", __func__,
825                     saidx->dst.sa.sa_family, saidx);
826         }
827
828         KEY_FREESAV(&sav);
829         return error;
830 bad:
831         if (sav)
832                 KEY_FREESAV(&sav);
833         if (m != NULL)
834                 m_freem(m);
835         if (tc != NULL)
836                 free(tc, M_XDATA);
837         if (crp != NULL)
838                 crypto_freereq(crp);
839         return error;
840 }
841
842 /*
843  * AH output routine, called by ipsec[46]_process_packet().
844  */
845 static int
846 ah_output(
847         struct mbuf *m,
848         struct ipsecrequest *isr,
849         struct mbuf **mp,
850         int skip,
851         int protoff)
852 {
853         struct secasvar *sav;
854         struct auth_hash *ahx;
855         struct cryptodesc *crda;
856         struct tdb_crypto *tc;
857         struct mbuf *mi;
858         struct cryptop *crp;
859         u_int16_t iplen;
860         int error, rplen, authsize, maxpacketsize, roff;
861         u_int8_t prot;
862         struct newah *ah;
863
864         sav = isr->sav;
865         IPSEC_ASSERT(sav != NULL, ("null SA"));
866         ahx = sav->tdb_authalgxform;
867         IPSEC_ASSERT(ahx != NULL, ("null authentication xform"));
868
869         AHSTAT_INC(ahs_output);
870
871         /* Figure out header size. */
872         rplen = HDRSIZE(sav);
873
874         /* Check for maximum packet size violations. */
875         switch (sav->sah->saidx.dst.sa.sa_family) {
876 #ifdef INET
877         case AF_INET:
878                 maxpacketsize = IP_MAXPACKET;
879                 break;
880 #endif /* INET */
881 #ifdef INET6
882         case AF_INET6:
883                 maxpacketsize = IPV6_MAXPACKET;
884                 break;
885 #endif /* INET6 */
886         default:
887                 DPRINTF(("%s: unknown/unsupported protocol family %u, "
888                     "SA %s/%08lx\n", __func__,
889                     sav->sah->saidx.dst.sa.sa_family,
890                     ipsec_address(&sav->sah->saidx.dst),
891                     (u_long) ntohl(sav->spi)));
892                 AHSTAT_INC(ahs_nopf);
893                 error = EPFNOSUPPORT;
894                 goto bad;
895         }
896         authsize = AUTHSIZE(sav);
897         if (rplen + authsize + m->m_pkthdr.len > maxpacketsize) {
898                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
899                     "(len %u, max len %u)\n", __func__,
900                     ipsec_address(&sav->sah->saidx.dst),
901                     (u_long) ntohl(sav->spi),
902                     rplen + authsize + m->m_pkthdr.len, maxpacketsize));
903                 AHSTAT_INC(ahs_toobig);
904                 error = EMSGSIZE;
905                 goto bad;
906         }
907
908         /* Update the counters. */
909         AHSTAT_ADD(ahs_obytes, m->m_pkthdr.len - skip);
910
911         m = m_unshare(m, M_NOWAIT);
912         if (m == NULL) {
913                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
914                     ipsec_address(&sav->sah->saidx.dst),
915                     (u_long) ntohl(sav->spi)));
916                 AHSTAT_INC(ahs_hdrops);
917                 error = ENOBUFS;
918                 goto bad;
919         }
920
921         /* Inject AH header. */
922         mi = m_makespace(m, skip, rplen + authsize, &roff);
923         if (mi == NULL) {
924                 DPRINTF(("%s: failed to inject %u byte AH header for SA "
925                     "%s/%08lx\n", __func__,
926                     rplen + authsize,
927                     ipsec_address(&sav->sah->saidx.dst),
928                     (u_long) ntohl(sav->spi)));
929                 AHSTAT_INC(ahs_hdrops);         /*XXX differs from openbsd */
930                 error = ENOBUFS;
931                 goto bad;
932         }
933
934         /*
935          * The AH header is guaranteed by m_makespace() to be in
936          * contiguous memory, at roff bytes offset into the returned mbuf.
937          */
938         ah = (struct newah *)(mtod(mi, caddr_t) + roff);
939
940         /* Initialize the AH header. */
941         m_copydata(m, protoff, sizeof(u_int8_t), (caddr_t) &ah->ah_nxt);
942         ah->ah_len = (rplen + authsize - sizeof(struct ah)) / sizeof(u_int32_t);
943         ah->ah_reserve = 0;
944         ah->ah_spi = sav->spi;
945
946         /* Zeroize authenticator. */
947         m_copyback(m, skip + rplen, authsize, ipseczeroes);
948
949         /* Insert packet replay counter, as requested.  */
950         if (sav->replay) {
951                 if (sav->replay->count == ~0 &&
952                     (sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
953                         DPRINTF(("%s: replay counter wrapped for SA %s/%08lx\n",
954                                 __func__,
955                                 ipsec_address(&sav->sah->saidx.dst),
956                                 (u_long) ntohl(sav->spi)));
957                         AHSTAT_INC(ahs_wrap);
958                         error = EINVAL;
959                         goto bad;
960                 }
961 #ifdef REGRESSION
962                 /* Emulate replay attack when ipsec_replay is TRUE. */
963                 if (!V_ipsec_replay)
964 #endif
965                         sav->replay->count++;
966                 ah->ah_seq = htonl(sav->replay->count);
967         }
968
969         /* Get crypto descriptors. */
970         crp = crypto_getreq(1);
971         if (crp == NULL) {
972                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
973                         __func__));
974                 AHSTAT_INC(ahs_crypto);
975                 error = ENOBUFS;
976                 goto bad;
977         }
978
979         crda = crp->crp_desc;
980
981         crda->crd_skip = 0;
982         crda->crd_inject = skip + rplen;
983         crda->crd_len = m->m_pkthdr.len;
984
985         /* Authentication operation. */
986         crda->crd_alg = ahx->type;
987         crda->crd_key = sav->key_auth->key_data;
988         crda->crd_klen = _KEYBITS(sav->key_auth);
989
990         /* Allocate IPsec-specific opaque crypto info. */
991         tc = (struct tdb_crypto *) malloc(
992                 sizeof(struct tdb_crypto) + skip, M_XDATA, M_NOWAIT|M_ZERO);
993         if (tc == NULL) {
994                 crypto_freereq(crp);
995                 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
996                 AHSTAT_INC(ahs_crypto);
997                 error = ENOBUFS;
998                 goto bad;
999         }
1000
1001         /* Save the skipped portion of the packet. */
1002         m_copydata(m, 0, skip, (caddr_t) (tc + 1));
1003
1004         /*
1005          * Fix IP header length on the header used for
1006          * authentication. We don't need to fix the original
1007          * header length as it will be fixed by our caller.
1008          */
1009         switch (sav->sah->saidx.dst.sa.sa_family) {
1010 #ifdef INET
1011         case AF_INET:
1012                 bcopy(((caddr_t)(tc + 1)) +
1013                     offsetof(struct ip, ip_len),
1014                     (caddr_t) &iplen, sizeof(u_int16_t));
1015                 iplen = htons(ntohs(iplen) + rplen + authsize);
1016                 m_copyback(m, offsetof(struct ip, ip_len),
1017                     sizeof(u_int16_t), (caddr_t) &iplen);
1018                 break;
1019 #endif /* INET */
1020
1021 #ifdef INET6
1022         case AF_INET6:
1023                 bcopy(((caddr_t)(tc + 1)) +
1024                     offsetof(struct ip6_hdr, ip6_plen),
1025                     (caddr_t) &iplen, sizeof(u_int16_t));
1026                 iplen = htons(ntohs(iplen) + rplen + authsize);
1027                 m_copyback(m, offsetof(struct ip6_hdr, ip6_plen),
1028                     sizeof(u_int16_t), (caddr_t) &iplen);
1029                 break;
1030 #endif /* INET6 */
1031         }
1032
1033         /* Fix the Next Header field in saved header. */
1034         ((u_int8_t *) (tc + 1))[protoff] = IPPROTO_AH;
1035
1036         /* Update the Next Protocol field in the IP header. */
1037         prot = IPPROTO_AH;
1038         m_copyback(m, protoff, sizeof(u_int8_t), (caddr_t) &prot);
1039
1040         /* "Massage" the packet headers for crypto processing. */
1041         error = ah_massage_headers(&m, sav->sah->saidx.dst.sa.sa_family,
1042                         skip, ahx->type, 1);
1043         if (error != 0) {
1044                 m = NULL;       /* mbuf was free'd by ah_massage_headers. */
1045                 free(tc, M_XDATA);
1046                 crypto_freereq(crp);
1047                 goto bad;
1048         }
1049
1050         /* Crypto operation descriptor. */
1051         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
1052         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
1053         crp->crp_buf = (caddr_t) m;
1054         crp->crp_callback = ah_output_cb;
1055         crp->crp_sid = sav->tdb_cryptoid;
1056         crp->crp_opaque = (caddr_t) tc;
1057
1058         /* These are passed as-is to the callback. */
1059         tc->tc_isr = isr;
1060         KEY_ADDREFSA(sav);
1061         tc->tc_sav = sav;
1062         tc->tc_spi = sav->spi;
1063         tc->tc_dst = sav->sah->saidx.dst;
1064         tc->tc_proto = sav->sah->saidx.proto;
1065         tc->tc_skip = skip;
1066         tc->tc_protoff = protoff;
1067
1068         return crypto_dispatch(crp);
1069 bad:
1070         if (m)
1071                 m_freem(m);
1072         return (error);
1073 }
1074
1075 /*
1076  * AH output callback from the crypto driver.
1077  */
1078 static int
1079 ah_output_cb(struct cryptop *crp)
1080 {
1081         int skip, protoff, error;
1082         struct tdb_crypto *tc;
1083         struct ipsecrequest *isr;
1084         struct secasvar *sav;
1085         struct mbuf *m;
1086         caddr_t ptr;
1087
1088         tc = (struct tdb_crypto *) crp->crp_opaque;
1089         IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
1090         skip = tc->tc_skip;
1091         protoff = tc->tc_protoff;
1092         ptr = (caddr_t) (tc + 1);
1093         m = (struct mbuf *) crp->crp_buf;
1094
1095         isr = tc->tc_isr;
1096         IPSECREQUEST_LOCK(isr);
1097         sav = tc->tc_sav;
1098         /* With the isr lock released SA pointer can be updated. */
1099         if (sav != isr->sav) {
1100                 AHSTAT_INC(ahs_notdb);
1101                 DPRINTF(("%s: SA expired while in crypto\n", __func__));
1102                 error = ENOBUFS;                /*XXX*/
1103                 goto bad;
1104         }
1105
1106         /* Check for crypto errors. */
1107         if (crp->crp_etype) {
1108                 if (sav->tdb_cryptoid != 0)
1109                         sav->tdb_cryptoid = crp->crp_sid;
1110
1111                 if (crp->crp_etype == EAGAIN) {
1112                         IPSECREQUEST_UNLOCK(isr);
1113                         return (crypto_dispatch(crp));
1114                 }
1115
1116                 AHSTAT_INC(ahs_noxform);
1117                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1118                 error = crp->crp_etype;
1119                 goto bad;
1120         }
1121
1122         /* Shouldn't happen... */
1123         if (m == NULL) {
1124                 AHSTAT_INC(ahs_crypto);
1125                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1126                 error = EINVAL;
1127                 goto bad;
1128         }
1129         AHSTAT_INC(ahs_hist[sav->alg_auth]);
1130
1131         /*
1132          * Copy original headers (with the new protocol number) back
1133          * in place.
1134          */
1135         m_copyback(m, 0, skip, ptr);
1136
1137         /* No longer needed. */
1138         free(tc, M_XDATA);
1139         crypto_freereq(crp);
1140
1141 #ifdef REGRESSION
1142         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1143         if (V_ipsec_integrity) {
1144                 int alen;
1145
1146                 /*
1147                  * Corrupt HMAC if we want to test integrity verification of
1148                  * the other side.
1149                  */
1150                 alen = AUTHSIZE(sav);
1151                 m_copyback(m, m->m_pkthdr.len - alen, alen, ipseczeroes);
1152         }
1153 #endif
1154
1155         /* NB: m is reclaimed by ipsec_process_done. */
1156         error = ipsec_process_done(m, isr);
1157         KEY_FREESAV(&sav);
1158         IPSECREQUEST_UNLOCK(isr);
1159         return error;
1160 bad:
1161         if (sav)
1162                 KEY_FREESAV(&sav);
1163         IPSECREQUEST_UNLOCK(isr);
1164         if (m)
1165                 m_freem(m);
1166         free(tc, M_XDATA);
1167         crypto_freereq(crp);
1168         return error;
1169 }
1170
1171 static struct xformsw ah_xformsw = {
1172         XF_AH,          XFT_AUTH,       "IPsec AH",
1173         ah_init,        ah_zeroize,     ah_input,       ah_output,
1174 };
1175
1176 static void
1177 ah_attach(void)
1178 {
1179
1180         xform_register(&ah_xformsw);
1181 }
1182
1183 SYSINIT(ah_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, ah_attach, NULL);