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