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