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