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