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