1/*	$NetBSD: umac.c,v 1.22 2023/07/26 17:58:16 christos Exp $	*/
2/* $OpenBSD: umac.c,v 1.23 2023/03/07 01:30:52 djm Exp $ */
3/* -----------------------------------------------------------------------
4 *
5 * umac.c -- C Implementation UMAC Message Authentication
6 *
7 * Version 0.93b of rfc4418.txt -- 2006 July 18
8 *
9 * For a full description of UMAC message authentication see the UMAC
10 * world-wide-web page at http://www.cs.ucdavis.edu/~rogaway/umac
11 * Please report bugs and suggestions to the UMAC webpage.
12 *
13 * Copyright (c) 1999-2006 Ted Krovetz
14 *
15 * Permission to use, copy, modify, and distribute this software and
16 * its documentation for any purpose and with or without fee, is hereby
17 * granted provided that the above copyright notice appears in all copies
18 * and in supporting documentation, and that the name of the copyright
19 * holder not be used in advertising or publicity pertaining to
20 * distribution of the software without specific, written prior permission.
21 *
22 * Comments should be directed to Ted Krovetz (tdk@acm.org)
23 *
24 * ---------------------------------------------------------------------- */
25
26 /* ////////////////////// IMPORTANT NOTES /////////////////////////////////
27  *
28  * 1) This version does not work properly on messages larger than 16MB
29  *
30  * 2) If you set the switch to use SSE2, then all data must be 16-byte
31  *    aligned
32  *
33  * 3) When calling the function umac(), it is assumed that msg is in
34  * a writable buffer of length divisible by 32 bytes. The message itself
35  * does not have to fill the entire buffer, but bytes beyond msg may be
36  * zeroed.
37  *
38  * 4) Three free AES implementations are supported by this implementation of
39  * UMAC. Paulo Barreto's version is in the public domain and can be found
40  * at http://www.esat.kuleuven.ac.be/~rijmen/rijndael/ (search for
41  * "Barreto"). The only two files needed are rijndael-alg-fst.c and
42  * rijndael-alg-fst.h. Brian Gladman's version is distributed with the GNU
43  * Public license at http://fp.gladman.plus.com/AES/index.htm. It
44  * includes a fast IA-32 assembly version. The OpenSSL crypo library is
45  * the third.
46  *
47  * 5) With FORCE_C_ONLY flags set to 0, incorrect results are sometimes
48  * produced under gcc with optimizations set -O3 or higher. Dunno why.
49  *
50  /////////////////////////////////////////////////////////////////////// */
51
52/* ---------------------------------------------------------------------- */
53/* --- User Switches ---------------------------------------------------- */
54/* ---------------------------------------------------------------------- */
55
56#ifndef UMAC_OUTPUT_LEN
57#define UMAC_OUTPUT_LEN     8  /* Alowable: 4, 8, 12, 16                  */
58#endif
59/* #define FORCE_C_ONLY        1  ANSI C and 64-bit integers req'd        */
60/* #define AES_IMPLEMENTAION   1  1 = OpenSSL, 2 = Barreto, 3 = Gladman   */
61/* #define SSE2                0  Is SSE2 is available?                   */
62/* #define RUN_TESTS           0  Run basic correctness/speed tests       */
63/* #define UMAC_AE_SUPPORT     0  Enable authenticated encryption         */
64
65/* ---------------------------------------------------------------------- */
66/* -- Global Includes --------------------------------------------------- */
67/* ---------------------------------------------------------------------- */
68
69#include "includes.h"
70__RCSID("$NetBSD: umac.c,v 1.22 2023/07/26 17:58:16 christos Exp $");
71#include <sys/types.h>
72#include <sys/endian.h>
73#include <string.h>
74#include <stdarg.h>
75#include <stdio.h>
76#include <stdlib.h>
77#include <stddef.h>
78#include <time.h>
79
80#include "xmalloc.h"
81#include "umac.h"
82#include "misc.h"
83
84/* ---------------------------------------------------------------------- */
85/* --- Primitive Data Types ---                                           */
86/* ---------------------------------------------------------------------- */
87
88/* The following assumptions may need change on your system */
89typedef u_int8_t	UINT8;  /* 1 byte   */
90typedef u_int16_t	UINT16; /* 2 byte   */
91typedef u_int32_t	UINT32; /* 4 byte   */
92typedef u_int64_t	UINT64; /* 8 bytes  */
93typedef unsigned int	UWORD;  /* Register */
94
95/* ---------------------------------------------------------------------- */
96/* --- Constants -------------------------------------------------------- */
97/* ---------------------------------------------------------------------- */
98
99#define UMAC_KEY_LEN           16  /* UMAC takes 16 bytes of external key */
100
101/* Message "words" are read from memory in an endian-specific manner.     */
102/* For this implementation to behave correctly, __LITTLE_ENDIAN__ must    */
103/* be set true if the host computer is little-endian.                     */
104
105#if BYTE_ORDER == LITTLE_ENDIAN
106#define __LITTLE_ENDIAN__ 1
107#else
108#define __LITTLE_ENDIAN__ 0
109#endif
110
111/* ---------------------------------------------------------------------- */
112/* ---------------------------------------------------------------------- */
113/* ----- Architecture Specific ------------------------------------------ */
114/* ---------------------------------------------------------------------- */
115/* ---------------------------------------------------------------------- */
116
117
118/* ---------------------------------------------------------------------- */
119/* ---------------------------------------------------------------------- */
120/* ----- Primitive Routines --------------------------------------------- */
121/* ---------------------------------------------------------------------- */
122/* ---------------------------------------------------------------------- */
123
124
125/* ---------------------------------------------------------------------- */
126/* --- 32-bit by 32-bit to 64-bit Multiplication ------------------------ */
127/* ---------------------------------------------------------------------- */
128
129#define MUL64(a,b) ((UINT64)((UINT64)(UINT32)(a) * (UINT64)(UINT32)(b)))
130
131/* ---------------------------------------------------------------------- */
132/* --- Endian Conversion --- Forcing assembly on some platforms           */
133/* ---------------------------------------------------------------------- */
134
135/* The following definitions use the above reversal-primitives to do the right
136 * thing on endian specific load and stores.
137 */
138
139#if BYTE_ORDER == LITTLE_ENDIAN
140#define LOAD_UINT32_REVERSED(p)		get_u32(p)
141#define STORE_UINT32_REVERSED(p,v)	put_u32(p,v)
142#else
143#define LOAD_UINT32_REVERSED(p)		get_u32_le(p)
144#define STORE_UINT32_REVERSED(p,v)	put_u32_le(p,v)
145#endif
146
147#define LOAD_UINT32_LITTLE(p)           (get_u32_le(p))
148#define STORE_UINT32_BIG(p,v)           put_u32(p, v)
149
150
151
152/* ---------------------------------------------------------------------- */
153/* ---------------------------------------------------------------------- */
154/* ----- Begin KDF & PDF Section ---------------------------------------- */
155/* ---------------------------------------------------------------------- */
156/* ---------------------------------------------------------------------- */
157
158/* UMAC uses AES with 16 byte block and key lengths */
159#define AES_BLOCK_LEN  16
160
161#ifdef WITH_OPENSSL
162#include <openssl/aes.h>
163typedef AES_KEY aes_int_key[1];
164#define aes_encryption(in,out,int_key)                  \
165  AES_encrypt((u_char *)(in),(u_char *)(out),(AES_KEY *)int_key)
166#define aes_key_setup(key,int_key)                      \
167  AES_set_encrypt_key((const u_char *)(key),UMAC_KEY_LEN*8,int_key)
168#else
169#include "rijndael.h"
170#define AES_ROUNDS ((UMAC_KEY_LEN / 4) + 6)
171typedef UINT8 aes_int_key[AES_ROUNDS+1][4][4];	/* AES internal */
172#define aes_encryption(in,out,int_key) \
173  rijndaelEncrypt((u32 *)(int_key), AES_ROUNDS, (u8 *)(in), (u8 *)(out))
174#define aes_key_setup(key,int_key) \
175  rijndaelKeySetupEnc((u32 *)(int_key), (const unsigned char *)(key), \
176  UMAC_KEY_LEN*8)
177#endif
178
179/* The user-supplied UMAC key is stretched using AES in a counter
180 * mode to supply all random bits needed by UMAC. The kdf function takes
181 * an AES internal key representation 'key' and writes a stream of
182 * 'nbytes' bytes to the memory pointed at by 'buffer_ptr'. Each distinct
183 * 'ndx' causes a distinct byte stream.
184 */
185static void kdf(void *buffer_ptr, aes_int_key key, UINT8 ndx, int nbytes)
186{
187    UINT8 in_buf[AES_BLOCK_LEN] = {0};
188    UINT8 out_buf[AES_BLOCK_LEN];
189    UINT8 *dst_buf = (UINT8 *)buffer_ptr;
190    int i;
191
192    /* Setup the initial value */
193    in_buf[AES_BLOCK_LEN-9] = ndx;
194    in_buf[AES_BLOCK_LEN-1] = i = 1;
195
196    while (nbytes >= AES_BLOCK_LEN) {
197        aes_encryption(in_buf, out_buf, key);
198        memcpy(dst_buf,out_buf,AES_BLOCK_LEN);
199        in_buf[AES_BLOCK_LEN-1] = ++i;
200        nbytes -= AES_BLOCK_LEN;
201        dst_buf += AES_BLOCK_LEN;
202    }
203    if (nbytes) {
204        aes_encryption(in_buf, out_buf, key);
205        memcpy(dst_buf,out_buf,nbytes);
206    }
207    explicit_bzero(in_buf, sizeof(in_buf));
208    explicit_bzero(out_buf, sizeof(out_buf));
209}
210
211/* The final UHASH result is XOR'd with the output of a pseudorandom
212 * function. Here, we use AES to generate random output and
213 * xor the appropriate bytes depending on the last bits of nonce.
214 * This scheme is optimized for sequential, increasing big-endian nonces.
215 */
216
217typedef struct {
218    UINT8 cache[AES_BLOCK_LEN];  /* Previous AES output is saved      */
219    UINT8 nonce[AES_BLOCK_LEN];  /* The AES input making above cache  */
220    aes_int_key prf_key;         /* Expanded AES key for PDF          */
221} pdf_ctx;
222
223static void pdf_init(pdf_ctx *pc, aes_int_key prf_key)
224{
225    UINT8 buf[UMAC_KEY_LEN];
226
227    kdf(buf, prf_key, 0, UMAC_KEY_LEN);
228    aes_key_setup(buf, pc->prf_key);
229
230    /* Initialize pdf and cache */
231    memset(pc->nonce, 0, sizeof(pc->nonce));
232    aes_encryption(pc->nonce, pc->cache, pc->prf_key);
233    explicit_bzero(buf, sizeof(buf));
234}
235
236static inline void
237xor64(uint8_t *dp, int di, uint8_t *sp, int si)
238{
239    uint64_t dst, src;
240    memcpy(&dst, dp + sizeof(dst) * di, sizeof(dst));
241    memcpy(&src, sp + sizeof(src) * si, sizeof(src));
242    dst ^= src;
243    memcpy(dp + sizeof(dst) * di, &dst, sizeof(dst));
244}
245
246__unused static inline void
247xor32(uint8_t *dp, int di, uint8_t *sp, int si)
248{
249    uint32_t dst, src;
250    memcpy(&dst, dp + sizeof(dst) * di, sizeof(dst));
251    memcpy(&src, sp + sizeof(src) * si, sizeof(src));
252    dst ^= src;
253    memcpy(dp + sizeof(dst) * di, &dst, sizeof(dst));
254}
255
256static void pdf_gen_xor(pdf_ctx *pc, const UINT8 nonce[8],
257    UINT8 buf[UMAC_OUTPUT_LEN])
258{
259    /* 'ndx' indicates that we'll be using the 0th or 1st eight bytes
260     * of the AES output. If last time around we returned the ndx-1st
261     * element, then we may have the result in the cache already.
262     */
263
264#if (UMAC_OUTPUT_LEN == 4)
265#define LOW_BIT_MASK 3
266#elif (UMAC_OUTPUT_LEN == 8)
267#define LOW_BIT_MASK 1
268#elif (UMAC_OUTPUT_LEN > 8)
269#define LOW_BIT_MASK 0
270#endif
271    union {
272        UINT8 tmp_nonce_lo[4];
273        UINT32 align;
274    } t;
275#if LOW_BIT_MASK != 0
276    int ndx = nonce[7] & LOW_BIT_MASK;
277#endif
278    memcpy(t.tmp_nonce_lo, nonce + 4, sizeof(t.tmp_nonce_lo));
279    t.tmp_nonce_lo[3] &= ~LOW_BIT_MASK; /* zero last bit */
280
281    if (memcmp(t.tmp_nonce_lo, pc->nonce + 1, sizeof(t.tmp_nonce_lo)) != 0 ||
282         memcmp(nonce, pc->nonce, sizeof(t.tmp_nonce_lo)) != 0)
283    {
284	memcpy(pc->nonce, nonce, sizeof(t.tmp_nonce_lo));
285	memcpy(pc->nonce + 4, t.tmp_nonce_lo, sizeof(t.tmp_nonce_lo));
286        aes_encryption(pc->nonce, pc->cache, pc->prf_key);
287    }
288
289#if (UMAC_OUTPUT_LEN == 4)
290    xor32(buf, 0, pc->cache, ndx);
291#elif (UMAC_OUTPUT_LEN == 8)
292    xor64(buf, 0, pc->cache, ndx);
293#elif (UMAC_OUTPUT_LEN == 12)
294    xor64(buf, 0, pc->cache, 0);
295    xor32(buf, 2, pc->cache, 2);
296#elif (UMAC_OUTPUT_LEN == 16)
297    xor64(buf, 0, pc->cache, 0);
298    xor64(buf, 1, pc->cache, 1);
299#endif
300}
301
302/* ---------------------------------------------------------------------- */
303/* ---------------------------------------------------------------------- */
304/* ----- Begin NH Hash Section ------------------------------------------ */
305/* ---------------------------------------------------------------------- */
306/* ---------------------------------------------------------------------- */
307
308/* The NH-based hash functions used in UMAC are described in the UMAC paper
309 * and specification, both of which can be found at the UMAC website.
310 * The interface to this implementation has two
311 * versions, one expects the entire message being hashed to be passed
312 * in a single buffer and returns the hash result immediately. The second
313 * allows the message to be passed in a sequence of buffers. In the
314 * multiple-buffer interface, the client calls the routine nh_update() as
315 * many times as necessary. When there is no more data to be fed to the
316 * hash, the client calls nh_final() which calculates the hash output.
317 * Before beginning another hash calculation the nh_reset() routine
318 * must be called. The single-buffer routine, nh(), is equivalent to
319 * the sequence of calls nh_update() and nh_final(); however it is
320 * optimized and should be preferred whenever the multiple-buffer interface
321 * is not necessary. When using either interface, it is the client's
322 * responsibility to pass no more than L1_KEY_LEN bytes per hash result.
323 *
324 * The routine nh_init() initializes the nh_ctx data structure and
325 * must be called once, before any other PDF routine.
326 */
327
328 /* The "nh_aux" routines do the actual NH hashing work. They
329  * expect buffers to be multiples of L1_PAD_BOUNDARY. These routines
330  * produce output for all STREAMS NH iterations in one call,
331  * allowing the parallel implementation of the streams.
332  */
333
334#define STREAMS (UMAC_OUTPUT_LEN / 4) /* Number of times hash is applied  */
335#define L1_KEY_LEN         1024     /* Internal key bytes                 */
336#define L1_KEY_SHIFT         16     /* Toeplitz key shift between streams */
337#define L1_PAD_BOUNDARY      32     /* pad message to boundary multiple   */
338#define ALLOC_BOUNDARY       16     /* Keep buffers aligned to this       */
339#define HASH_BUF_BYTES       64     /* nh_aux_hb buffer multiple          */
340
341typedef struct {
342    UINT8  nh_key [L1_KEY_LEN + L1_KEY_SHIFT * (STREAMS - 1)]; /* NH Key */
343    UINT8  data   [HASH_BUF_BYTES];    /* Incoming data buffer           */
344    int next_data_empty;    /* Bookkeeping variable for data buffer.     */
345    int bytes_hashed;       /* Bytes (out of L1_KEY_LEN) incorporated.   */
346    UINT64 state[STREAMS];               /* on-line state     */
347} nh_ctx;
348
349
350#if (UMAC_OUTPUT_LEN == 4)
351
352static void nh_aux(void *kp, const void *dp, void *hp, UINT32 dlen)
353/* NH hashing primitive. Previous (partial) hash result is loaded and
354* then stored via hp pointer. The length of the data pointed at by "dp",
355* "dlen", is guaranteed to be divisible by L1_PAD_BOUNDARY (32).  Key
356* is expected to be endian compensated in memory at key setup.
357*/
358{
359    UINT64 h;
360    UWORD c = dlen / 32;
361    UINT32 *k = (UINT32 *)kp;
362    const UINT32 *d = (const UINT32 *)dp;
363    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
364    UINT32 k0,k1,k2,k3,k4,k5,k6,k7;
365
366    h = *((UINT64 *)hp);
367    do {
368        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
369        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
370        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
371        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
372        k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
373        k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
374        h += MUL64((k0 + d0), (k4 + d4));
375        h += MUL64((k1 + d1), (k5 + d5));
376        h += MUL64((k2 + d2), (k6 + d6));
377        h += MUL64((k3 + d3), (k7 + d7));
378
379        d += 8;
380        k += 8;
381    } while (--c);
382  *((UINT64 *)hp) = h;
383}
384
385#elif (UMAC_OUTPUT_LEN == 8)
386
387static void nh_aux(void *kp, const void *dp, void *hp, UINT32 dlen)
388/* Same as previous nh_aux, but two streams are handled in one pass,
389 * reading and writing 16 bytes of hash-state per call.
390 */
391{
392  UINT64 h1,h2;
393  UWORD c = dlen / 32;
394  UINT32 *k = (UINT32 *)kp;
395  const UINT32 *d = (const UINT32 *)dp;
396  UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
397  UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
398        k8,k9,k10,k11;
399
400  h1 = *((UINT64 *)hp);
401  h2 = *((UINT64 *)hp + 1);
402  k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
403  do {
404    d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
405    d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
406    d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
407    d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
408    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
409    k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
410
411    h1 += MUL64((k0 + d0), (k4 + d4));
412    h2 += MUL64((k4 + d0), (k8 + d4));
413
414    h1 += MUL64((k1 + d1), (k5 + d5));
415    h2 += MUL64((k5 + d1), (k9 + d5));
416
417    h1 += MUL64((k2 + d2), (k6 + d6));
418    h2 += MUL64((k6 + d2), (k10 + d6));
419
420    h1 += MUL64((k3 + d3), (k7 + d7));
421    h2 += MUL64((k7 + d3), (k11 + d7));
422
423    k0 = k8; k1 = k9; k2 = k10; k3 = k11;
424
425    d += 8;
426    k += 8;
427  } while (--c);
428  ((UINT64 *)hp)[0] = h1;
429  ((UINT64 *)hp)[1] = h2;
430}
431
432#elif (UMAC_OUTPUT_LEN == 12)
433
434static void nh_aux(void *kp, const void *dp, void *hp, UINT32 dlen)
435/* Same as previous nh_aux, but two streams are handled in one pass,
436 * reading and writing 24 bytes of hash-state per call.
437*/
438{
439    UINT64 h1,h2,h3;
440    UWORD c = dlen / 32;
441    UINT32 *k = (UINT32 *)kp;
442    const UINT32 *d = (const UINT32 *)dp;
443    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
444    UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
445        k8,k9,k10,k11,k12,k13,k14,k15;
446
447    h1 = *((UINT64 *)hp);
448    h2 = *((UINT64 *)hp + 1);
449    h3 = *((UINT64 *)hp + 2);
450    k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
451    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
452    do {
453        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
454        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
455        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
456        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
457        k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
458        k12 = *(k+12); k13 = *(k+13); k14 = *(k+14); k15 = *(k+15);
459
460        h1 += MUL64((k0 + d0), (k4 + d4));
461        h2 += MUL64((k4 + d0), (k8 + d4));
462        h3 += MUL64((k8 + d0), (k12 + d4));
463
464        h1 += MUL64((k1 + d1), (k5 + d5));
465        h2 += MUL64((k5 + d1), (k9 + d5));
466        h3 += MUL64((k9 + d1), (k13 + d5));
467
468        h1 += MUL64((k2 + d2), (k6 + d6));
469        h2 += MUL64((k6 + d2), (k10 + d6));
470        h3 += MUL64((k10 + d2), (k14 + d6));
471
472        h1 += MUL64((k3 + d3), (k7 + d7));
473        h2 += MUL64((k7 + d3), (k11 + d7));
474        h3 += MUL64((k11 + d3), (k15 + d7));
475
476        k0 = k8; k1 = k9; k2 = k10; k3 = k11;
477        k4 = k12; k5 = k13; k6 = k14; k7 = k15;
478
479        d += 8;
480        k += 8;
481    } while (--c);
482    ((UINT64 *)hp)[0] = h1;
483    ((UINT64 *)hp)[1] = h2;
484    ((UINT64 *)hp)[2] = h3;
485}
486
487#elif (UMAC_OUTPUT_LEN == 16)
488
489static void nh_aux(void *kp, const void *dp, void *hp, UINT32 dlen)
490/* Same as previous nh_aux, but two streams are handled in one pass,
491 * reading and writing 24 bytes of hash-state per call.
492*/
493{
494    UINT64 h1,h2,h3,h4;
495    UWORD c = dlen / 32;
496    UINT32 *k = (UINT32 *)kp;
497    const UINT32 *d = (const UINT32 *)dp;
498    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
499    UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
500        k8,k9,k10,k11,k12,k13,k14,k15,
501        k16,k17,k18,k19;
502
503    h1 = *((UINT64 *)hp);
504    h2 = *((UINT64 *)hp + 1);
505    h3 = *((UINT64 *)hp + 2);
506    h4 = *((UINT64 *)hp + 3);
507    k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
508    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
509    do {
510        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
511        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
512        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
513        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
514        k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
515        k12 = *(k+12); k13 = *(k+13); k14 = *(k+14); k15 = *(k+15);
516        k16 = *(k+16); k17 = *(k+17); k18 = *(k+18); k19 = *(k+19);
517
518        h1 += MUL64((k0 + d0), (k4 + d4));
519        h2 += MUL64((k4 + d0), (k8 + d4));
520        h3 += MUL64((k8 + d0), (k12 + d4));
521        h4 += MUL64((k12 + d0), (k16 + d4));
522
523        h1 += MUL64((k1 + d1), (k5 + d5));
524        h2 += MUL64((k5 + d1), (k9 + d5));
525        h3 += MUL64((k9 + d1), (k13 + d5));
526        h4 += MUL64((k13 + d1), (k17 + d5));
527
528        h1 += MUL64((k2 + d2), (k6 + d6));
529        h2 += MUL64((k6 + d2), (k10 + d6));
530        h3 += MUL64((k10 + d2), (k14 + d6));
531        h4 += MUL64((k14 + d2), (k18 + d6));
532
533        h1 += MUL64((k3 + d3), (k7 + d7));
534        h2 += MUL64((k7 + d3), (k11 + d7));
535        h3 += MUL64((k11 + d3), (k15 + d7));
536        h4 += MUL64((k15 + d3), (k19 + d7));
537
538        k0 = k8; k1 = k9; k2 = k10; k3 = k11;
539        k4 = k12; k5 = k13; k6 = k14; k7 = k15;
540        k8 = k16; k9 = k17; k10 = k18; k11 = k19;
541
542        d += 8;
543        k += 8;
544    } while (--c);
545    ((UINT64 *)hp)[0] = h1;
546    ((UINT64 *)hp)[1] = h2;
547    ((UINT64 *)hp)[2] = h3;
548    ((UINT64 *)hp)[3] = h4;
549}
550
551/* ---------------------------------------------------------------------- */
552#endif  /* UMAC_OUTPUT_LENGTH */
553/* ---------------------------------------------------------------------- */
554
555
556/* ---------------------------------------------------------------------- */
557
558static void nh_transform(nh_ctx *hc, const UINT8 *buf, UINT32 nbytes)
559/* This function is a wrapper for the primitive NH hash functions. It takes
560 * as argument "hc" the current hash context and a buffer which must be a
561 * multiple of L1_PAD_BOUNDARY. The key passed to nh_aux is offset
562 * appropriately according to how much message has been hashed already.
563 */
564{
565    UINT8 *key;
566
567    key = hc->nh_key + hc->bytes_hashed;
568    nh_aux(key, buf, hc->state, nbytes);
569}
570
571/* ---------------------------------------------------------------------- */
572
573#if (__LITTLE_ENDIAN__)
574static void endian_convert(void *buf, UWORD bpw, UINT32 num_bytes)
575/* We endian convert the keys on little-endian computers to               */
576/* compensate for the lack of big-endian memory reads during hashing.     */
577{
578    UWORD iters = num_bytes / bpw;
579    if (bpw == 4) {
580        UINT32 *p = (UINT32 *)buf;
581        do {
582            *p = LOAD_UINT32_REVERSED(p);
583            p++;
584        } while (--iters);
585    } else if (bpw == 8) {
586        UINT64 *p = (UINT64 *)buf;
587        UINT64 th;
588        UINT64 t;
589        do {
590            t = LOAD_UINT32_REVERSED((UINT32 *)p+1);
591            th = LOAD_UINT32_REVERSED((UINT32 *)p);
592            *p++ = t | (th << 32);
593        } while (--iters);
594    }
595}
596#define endian_convert_if_le(x,y,z) endian_convert((x),(y),(z))
597#else
598#define endian_convert_if_le(x,y,z) do{}while(0)  /* Do nothing */
599#endif
600
601/* ---------------------------------------------------------------------- */
602
603static void nh_reset(nh_ctx *hc)
604/* Reset nh_ctx to ready for hashing of new data */
605{
606    hc->bytes_hashed = 0;
607    hc->next_data_empty = 0;
608    hc->state[0] = 0;
609#if (UMAC_OUTPUT_LEN >= 8)
610    hc->state[1] = 0;
611#endif
612#if (UMAC_OUTPUT_LEN >= 12)
613    hc->state[2] = 0;
614#endif
615#if (UMAC_OUTPUT_LEN == 16)
616    hc->state[3] = 0;
617#endif
618
619}
620
621/* ---------------------------------------------------------------------- */
622
623static void nh_init(nh_ctx *hc, aes_int_key prf_key)
624/* Generate nh_key, endian convert and reset to be ready for hashing.   */
625{
626    kdf(hc->nh_key, prf_key, 1, sizeof(hc->nh_key));
627    endian_convert_if_le(hc->nh_key, 4, sizeof(hc->nh_key));
628    nh_reset(hc);
629}
630
631/* ---------------------------------------------------------------------- */
632
633static void nh_update(nh_ctx *hc, const UINT8 *buf, UINT32 nbytes)
634/* Incorporate nbytes of data into a nh_ctx, buffer whatever is not an    */
635/* even multiple of HASH_BUF_BYTES.                                       */
636{
637    UINT32 i,j;
638
639    j = hc->next_data_empty;
640    if ((j + nbytes) >= HASH_BUF_BYTES) {
641        if (j) {
642            i = HASH_BUF_BYTES - j;
643            memcpy(hc->data+j, buf, i);
644            nh_transform(hc,hc->data,HASH_BUF_BYTES);
645            nbytes -= i;
646            buf += i;
647            hc->bytes_hashed += HASH_BUF_BYTES;
648        }
649        if (nbytes >= HASH_BUF_BYTES) {
650            i = nbytes & ~(HASH_BUF_BYTES - 1);
651            nh_transform(hc, buf, i);
652            nbytes -= i;
653            buf += i;
654            hc->bytes_hashed += i;
655        }
656        j = 0;
657    }
658    memcpy(hc->data + j, buf, nbytes);
659    hc->next_data_empty = j + nbytes;
660}
661
662/* ---------------------------------------------------------------------- */
663
664static void zero_pad(UINT8 *p, int nbytes)
665{
666/* Write "nbytes" of zeroes, beginning at "p" */
667    if (nbytes >= (int)sizeof(UWORD)) {
668        while ((ptrdiff_t)p % sizeof(UWORD)) {
669            *p = 0;
670            nbytes--;
671            p++;
672        }
673        while (nbytes >= (int)sizeof(UWORD)) {
674            *(UWORD *)p = 0;
675            nbytes -= sizeof(UWORD);
676            p += sizeof(UWORD);
677        }
678    }
679    while (nbytes) {
680        *p = 0;
681        nbytes--;
682        p++;
683    }
684}
685
686/* ---------------------------------------------------------------------- */
687
688static void nh_final(nh_ctx *hc, UINT8 *result)
689/* After passing some number of data buffers to nh_update() for integration
690 * into an NH context, nh_final is called to produce a hash result. If any
691 * bytes are in the buffer hc->data, incorporate them into the
692 * NH context. Finally, add into the NH accumulation "state" the total number
693 * of bits hashed. The resulting numbers are written to the buffer "result".
694 * If nh_update was never called, L1_PAD_BOUNDARY zeroes are incorporated.
695 */
696{
697    int nh_len, nbits;
698
699    if (hc->next_data_empty != 0) {
700        nh_len = ((hc->next_data_empty + (L1_PAD_BOUNDARY - 1)) &
701                                                ~(L1_PAD_BOUNDARY - 1));
702        zero_pad(hc->data + hc->next_data_empty,
703                                          nh_len - hc->next_data_empty);
704        nh_transform(hc, hc->data, nh_len);
705        hc->bytes_hashed += hc->next_data_empty;
706    } else if (hc->bytes_hashed == 0) {
707	nh_len = L1_PAD_BOUNDARY;
708        zero_pad(hc->data, L1_PAD_BOUNDARY);
709        nh_transform(hc, hc->data, nh_len);
710    }
711
712    nbits = (hc->bytes_hashed << 3);
713    ((UINT64 *)result)[0] = ((UINT64 *)hc->state)[0] + nbits;
714#if (UMAC_OUTPUT_LEN >= 8)
715    ((UINT64 *)result)[1] = ((UINT64 *)hc->state)[1] + nbits;
716#endif
717#if (UMAC_OUTPUT_LEN >= 12)
718    ((UINT64 *)result)[2] = ((UINT64 *)hc->state)[2] + nbits;
719#endif
720#if (UMAC_OUTPUT_LEN == 16)
721    ((UINT64 *)result)[3] = ((UINT64 *)hc->state)[3] + nbits;
722#endif
723    nh_reset(hc);
724}
725
726/* ---------------------------------------------------------------------- */
727
728static void nh(nh_ctx *hc, const UINT8 *buf, UINT32 padded_len,
729               UINT32 unpadded_len, UINT8 *result)
730/* All-in-one nh_update() and nh_final() equivalent.
731 * Assumes that padded_len is divisible by L1_PAD_BOUNDARY and result is
732 * well aligned
733 */
734{
735    UINT32 nbits;
736
737    /* Initialize the hash state */
738    nbits = (unpadded_len << 3);
739
740    ((UINT64 *)result)[0] = nbits;
741#if (UMAC_OUTPUT_LEN >= 8)
742    ((UINT64 *)result)[1] = nbits;
743#endif
744#if (UMAC_OUTPUT_LEN >= 12)
745    ((UINT64 *)result)[2] = nbits;
746#endif
747#if (UMAC_OUTPUT_LEN == 16)
748    ((UINT64 *)result)[3] = nbits;
749#endif
750
751    nh_aux(hc->nh_key, buf, result, padded_len);
752}
753
754/* ---------------------------------------------------------------------- */
755/* ---------------------------------------------------------------------- */
756/* ----- Begin UHASH Section -------------------------------------------- */
757/* ---------------------------------------------------------------------- */
758/* ---------------------------------------------------------------------- */
759
760/* UHASH is a multi-layered algorithm. Data presented to UHASH is first
761 * hashed by NH. The NH output is then hashed by a polynomial-hash layer
762 * unless the initial data to be hashed is short. After the polynomial-
763 * layer, an inner-product hash is used to produce the final UHASH output.
764 *
765 * UHASH provides two interfaces, one all-at-once and another where data
766 * buffers are presented sequentially. In the sequential interface, the
767 * UHASH client calls the routine uhash_update() as many times as necessary.
768 * When there is no more data to be fed to UHASH, the client calls
769 * uhash_final() which
770 * calculates the UHASH output. Before beginning another UHASH calculation
771 * the uhash_reset() routine must be called. The all-at-once UHASH routine,
772 * uhash(), is equivalent to the sequence of calls uhash_update() and
773 * uhash_final(); however it is optimized and should be
774 * used whenever the sequential interface is not necessary.
775 *
776 * The routine uhash_init() initializes the uhash_ctx data structure and
777 * must be called once, before any other UHASH routine.
778 */
779
780/* ---------------------------------------------------------------------- */
781/* ----- Constants and uhash_ctx ---------------------------------------- */
782/* ---------------------------------------------------------------------- */
783
784/* ---------------------------------------------------------------------- */
785/* ----- Poly hash and Inner-Product hash Constants --------------------- */
786/* ---------------------------------------------------------------------- */
787
788/* Primes and masks */
789#define p36    ((UINT64)0x0000000FFFFFFFFBull)              /* 2^36 -  5 */
790#define p64    ((UINT64)0xFFFFFFFFFFFFFFC5ull)              /* 2^64 - 59 */
791#define m36    ((UINT64)0x0000000FFFFFFFFFull)  /* The low 36 of 64 bits */
792
793
794/* ---------------------------------------------------------------------- */
795
796typedef struct uhash_ctx {
797    nh_ctx hash;                          /* Hash context for L1 NH hash  */
798    UINT64 poly_key_8[STREAMS];           /* p64 poly keys                */
799    UINT64 poly_accum[STREAMS];           /* poly hash result             */
800    UINT64 ip_keys[STREAMS*4];            /* Inner-product keys           */
801    UINT32 ip_trans[STREAMS];             /* Inner-product translation    */
802    UINT32 msg_len;                       /* Total length of data passed  */
803                                          /* to uhash */
804} uhash_ctx;
805typedef struct uhash_ctx *uhash_ctx_t;
806
807/* ---------------------------------------------------------------------- */
808
809
810/* The polynomial hashes use Horner's rule to evaluate a polynomial one
811 * word at a time. As described in the specification, poly32 and poly64
812 * require keys from special domains. The following implementations exploit
813 * the special domains to avoid overflow. The results are not guaranteed to
814 * be within Z_p32 and Z_p64, but the Inner-Product hash implementation
815 * patches any errant values.
816 */
817
818static UINT64 poly64(UINT64 cur, UINT64 key, UINT64 data)
819{
820    UINT32 key_hi = (UINT32)(key >> 32),
821           key_lo = (UINT32)key,
822           cur_hi = (UINT32)(cur >> 32),
823           cur_lo = (UINT32)cur,
824           x_lo,
825           x_hi;
826    UINT64 X,T,res;
827
828    X =  MUL64(key_hi, cur_lo) + MUL64(cur_hi, key_lo);
829    x_lo = (UINT32)X;
830    x_hi = (UINT32)(X >> 32);
831
832    res = (MUL64(key_hi, cur_hi) + x_hi) * 59 + MUL64(key_lo, cur_lo);
833
834    T = ((UINT64)x_lo << 32);
835    res += T;
836    if (res < T)
837        res += 59;
838
839    res += data;
840    if (res < data)
841        res += 59;
842
843    return res;
844}
845
846
847/* Although UMAC is specified to use a ramped polynomial hash scheme, this
848 * implementation does not handle all ramp levels. Because we don't handle
849 * the ramp up to p128 modulus in this implementation, we are limited to
850 * 2^14 poly_hash() invocations per stream (for a total capacity of 2^24
851 * bytes input to UMAC per tag, ie. 16MB).
852 */
853static void poly_hash(uhash_ctx_t hc, UINT32 data_in[])
854{
855    int i;
856    UINT64 *data=(UINT64*)data_in;
857
858    for (i = 0; i < STREAMS; i++) {
859        if ((UINT32)(data[i] >> 32) == 0xfffffffful) {
860            hc->poly_accum[i] = poly64(hc->poly_accum[i],
861                                       hc->poly_key_8[i], p64 - 1);
862            hc->poly_accum[i] = poly64(hc->poly_accum[i],
863                                       hc->poly_key_8[i], (data[i] - 59));
864        } else {
865            hc->poly_accum[i] = poly64(hc->poly_accum[i],
866                                       hc->poly_key_8[i], data[i]);
867        }
868    }
869}
870
871
872/* ---------------------------------------------------------------------- */
873
874
875/* The final step in UHASH is an inner-product hash. The poly hash
876 * produces a result not necessarily WORD_LEN bytes long. The inner-
877 * product hash breaks the polyhash output into 16-bit chunks and
878 * multiplies each with a 36 bit key.
879 */
880
881static UINT64 ip_aux(UINT64 t, UINT64 *ipkp, UINT64 data)
882{
883    t = t + ipkp[0] * (UINT64)(UINT16)(data >> 48);
884    t = t + ipkp[1] * (UINT64)(UINT16)(data >> 32);
885    t = t + ipkp[2] * (UINT64)(UINT16)(data >> 16);
886    t = t + ipkp[3] * (UINT64)(UINT16)(data);
887
888    return t;
889}
890
891static UINT32 ip_reduce_p36(UINT64 t)
892{
893/* Divisionless modular reduction */
894    UINT64 ret;
895
896    ret = (t & m36) + 5 * (t >> 36);
897    if (ret >= p36)
898        ret -= p36;
899
900    /* return least significant 32 bits */
901    return (UINT32)(ret);
902}
903
904
905/* If the data being hashed by UHASH is no longer than L1_KEY_LEN, then
906 * the polyhash stage is skipped and ip_short is applied directly to the
907 * NH output.
908 */
909static void ip_short(uhash_ctx_t ahc, UINT8 *nh_res, u_char *res)
910{
911    UINT64 t;
912    UINT64 *nhp = (UINT64 *)nh_res;
913
914    t  = ip_aux(0,ahc->ip_keys, nhp[0]);
915    STORE_UINT32_BIG((UINT32 *)res+0, ip_reduce_p36(t) ^ ahc->ip_trans[0]);
916#if (UMAC_OUTPUT_LEN >= 8)
917    t  = ip_aux(0,ahc->ip_keys+4, nhp[1]);
918    STORE_UINT32_BIG((UINT32 *)res+1, ip_reduce_p36(t) ^ ahc->ip_trans[1]);
919#endif
920#if (UMAC_OUTPUT_LEN >= 12)
921    t  = ip_aux(0,ahc->ip_keys+8, nhp[2]);
922    STORE_UINT32_BIG((UINT32 *)res+2, ip_reduce_p36(t) ^ ahc->ip_trans[2]);
923#endif
924#if (UMAC_OUTPUT_LEN == 16)
925    t  = ip_aux(0,ahc->ip_keys+12, nhp[3]);
926    STORE_UINT32_BIG((UINT32 *)res+3, ip_reduce_p36(t) ^ ahc->ip_trans[3]);
927#endif
928}
929
930/* If the data being hashed by UHASH is longer than L1_KEY_LEN, then
931 * the polyhash stage is not skipped and ip_long is applied to the
932 * polyhash output.
933 */
934static void ip_long(uhash_ctx_t ahc, u_char *res)
935{
936    int i;
937    UINT64 t;
938
939    for (i = 0; i < STREAMS; i++) {
940        /* fix polyhash output not in Z_p64 */
941        if (ahc->poly_accum[i] >= p64)
942            ahc->poly_accum[i] -= p64;
943        t  = ip_aux(0,ahc->ip_keys+(i*4), ahc->poly_accum[i]);
944        STORE_UINT32_BIG((UINT32 *)res+i,
945                         ip_reduce_p36(t) ^ ahc->ip_trans[i]);
946    }
947}
948
949
950/* ---------------------------------------------------------------------- */
951
952/* ---------------------------------------------------------------------- */
953
954/* Reset uhash context for next hash session */
955static int uhash_reset(uhash_ctx_t pc)
956{
957    nh_reset(&pc->hash);
958    pc->msg_len = 0;
959    pc->poly_accum[0] = 1;
960#if (UMAC_OUTPUT_LEN >= 8)
961    pc->poly_accum[1] = 1;
962#endif
963#if (UMAC_OUTPUT_LEN >= 12)
964    pc->poly_accum[2] = 1;
965#endif
966#if (UMAC_OUTPUT_LEN == 16)
967    pc->poly_accum[3] = 1;
968#endif
969    return 1;
970}
971
972/* ---------------------------------------------------------------------- */
973
974/* Given a pointer to the internal key needed by kdf() and a uhash context,
975 * initialize the NH context and generate keys needed for poly and inner-
976 * product hashing. All keys are endian adjusted in memory so that native
977 * loads cause correct keys to be in registers during calculation.
978 */
979static void uhash_init(uhash_ctx_t ahc, aes_int_key prf_key)
980{
981    int i;
982    UINT8 buf[(8*STREAMS+4)*sizeof(UINT64)];
983
984    /* Zero the entire uhash context */
985    memset(ahc, 0, sizeof(uhash_ctx));
986
987    /* Initialize the L1 hash */
988    nh_init(&ahc->hash, prf_key);
989
990    /* Setup L2 hash variables */
991    kdf(buf, prf_key, 2, sizeof(buf));    /* Fill buffer with index 1 key */
992    for (i = 0; i < STREAMS; i++) {
993        /* Fill keys from the buffer, skipping bytes in the buffer not
994         * used by this implementation. Endian reverse the keys if on a
995         * little-endian computer.
996         */
997        memcpy(ahc->poly_key_8+i, buf+24*i, 8);
998        endian_convert_if_le(ahc->poly_key_8+i, 8, 8);
999        /* Mask the 64-bit keys to their special domain */
1000        ahc->poly_key_8[i] &= ((UINT64)0x01ffffffu << 32) + 0x01ffffffu;
1001        ahc->poly_accum[i] = 1;  /* Our polyhash prepends a non-zero word */
1002    }
1003
1004    /* Setup L3-1 hash variables */
1005    kdf(buf, prf_key, 3, sizeof(buf)); /* Fill buffer with index 2 key */
1006    for (i = 0; i < STREAMS; i++)
1007          memcpy(ahc->ip_keys+4*i, buf+(8*i+4)*sizeof(UINT64),
1008                                                 4*sizeof(UINT64));
1009    endian_convert_if_le(ahc->ip_keys, sizeof(UINT64),
1010                                                  sizeof(ahc->ip_keys));
1011    for (i = 0; i < STREAMS*4; i++)
1012        ahc->ip_keys[i] %= p36;  /* Bring into Z_p36 */
1013
1014    /* Setup L3-2 hash variables    */
1015    /* Fill buffer with index 4 key */
1016    kdf(ahc->ip_trans, prf_key, 4, STREAMS * sizeof(UINT32));
1017    endian_convert_if_le(ahc->ip_trans, sizeof(UINT32),
1018                         STREAMS * sizeof(UINT32));
1019    explicit_bzero(buf, sizeof(buf));
1020}
1021
1022/* ---------------------------------------------------------------------- */
1023
1024#if 0
1025static uhash_ctx_t uhash_alloc(u_char key[])
1026{
1027/* Allocate memory and force to a 16-byte boundary. */
1028    uhash_ctx_t ctx;
1029    u_char bytes_to_add;
1030    aes_int_key prf_key;
1031
1032    ctx = (uhash_ctx_t)malloc(sizeof(uhash_ctx)+ALLOC_BOUNDARY);
1033    if (ctx) {
1034        if (ALLOC_BOUNDARY) {
1035            bytes_to_add = ALLOC_BOUNDARY -
1036                              ((ptrdiff_t)ctx & (ALLOC_BOUNDARY -1));
1037            ctx = (uhash_ctx_t)((u_char *)ctx + bytes_to_add);
1038            *((u_char *)ctx - 1) = bytes_to_add;
1039        }
1040        aes_key_setup(key,prf_key);
1041        uhash_init(ctx, prf_key);
1042    }
1043    return (ctx);
1044}
1045#endif
1046
1047/* ---------------------------------------------------------------------- */
1048
1049#if 0
1050static int uhash_free(uhash_ctx_t ctx)
1051{
1052/* Free memory allocated by uhash_alloc */
1053    u_char bytes_to_sub;
1054
1055    if (ctx) {
1056        if (ALLOC_BOUNDARY) {
1057            bytes_to_sub = *((u_char *)ctx - 1);
1058            ctx = (uhash_ctx_t)((u_char *)ctx - bytes_to_sub);
1059        }
1060        free(ctx);
1061    }
1062    return (1);
1063}
1064#endif
1065/* ---------------------------------------------------------------------- */
1066
1067static int uhash_update(uhash_ctx_t ctx, const u_char *input, long len)
1068/* Given len bytes of data, we parse it into L1_KEY_LEN chunks and
1069 * hash each one with NH, calling the polyhash on each NH output.
1070 */
1071{
1072    UWORD bytes_hashed, bytes_remaining;
1073    UINT64 result_buf[STREAMS];
1074    UINT8 *nh_result = (UINT8 *)&result_buf;
1075
1076    if (ctx->msg_len + len <= L1_KEY_LEN) {
1077        nh_update(&ctx->hash, (const UINT8 *)input, len);
1078        ctx->msg_len += len;
1079    } else {
1080
1081         bytes_hashed = ctx->msg_len % L1_KEY_LEN;
1082         if (ctx->msg_len == L1_KEY_LEN)
1083             bytes_hashed = L1_KEY_LEN;
1084
1085         if (bytes_hashed + len >= L1_KEY_LEN) {
1086
1087             /* If some bytes have been passed to the hash function      */
1088             /* then we want to pass at most (L1_KEY_LEN - bytes_hashed) */
1089             /* bytes to complete the current nh_block.                  */
1090             if (bytes_hashed) {
1091                 bytes_remaining = (L1_KEY_LEN - bytes_hashed);
1092                 nh_update(&ctx->hash, (const UINT8 *)input, bytes_remaining);
1093                 nh_final(&ctx->hash, nh_result);
1094                 ctx->msg_len += bytes_remaining;
1095                 poly_hash(ctx,(UINT32 *)nh_result);
1096                 len -= bytes_remaining;
1097                 input += bytes_remaining;
1098             }
1099
1100             /* Hash directly from input stream if enough bytes */
1101             while (len >= L1_KEY_LEN) {
1102                 nh(&ctx->hash, (const UINT8 *)input, L1_KEY_LEN,
1103                                   L1_KEY_LEN, nh_result);
1104                 ctx->msg_len += L1_KEY_LEN;
1105                 len -= L1_KEY_LEN;
1106                 input += L1_KEY_LEN;
1107                 poly_hash(ctx,(UINT32 *)nh_result);
1108             }
1109         }
1110
1111         /* pass remaining < L1_KEY_LEN bytes of input data to NH */
1112         if (len) {
1113             nh_update(&ctx->hash, (const UINT8 *)input, len);
1114             ctx->msg_len += len;
1115         }
1116     }
1117
1118    return (1);
1119}
1120
1121/* ---------------------------------------------------------------------- */
1122
1123static int uhash_final(uhash_ctx_t ctx, u_char *res)
1124/* Incorporate any pending data, pad, and generate tag */
1125{
1126    UINT64 result_buf[STREAMS];
1127    UINT8 *nh_result = (UINT8 *)&result_buf;
1128
1129    if (ctx->msg_len > L1_KEY_LEN) {
1130        if (ctx->msg_len % L1_KEY_LEN) {
1131            nh_final(&ctx->hash, nh_result);
1132            poly_hash(ctx,(UINT32 *)nh_result);
1133        }
1134        ip_long(ctx, res);
1135    } else {
1136        nh_final(&ctx->hash, nh_result);
1137        ip_short(ctx,nh_result, res);
1138    }
1139    uhash_reset(ctx);
1140    return (1);
1141}
1142
1143/* ---------------------------------------------------------------------- */
1144
1145#if 0
1146static int uhash(uhash_ctx_t ahc, u_char *msg, long len, u_char *res)
1147/* assumes that msg is in a writable buffer of length divisible by */
1148/* L1_PAD_BOUNDARY. Bytes beyond msg[len] may be zeroed.           */
1149{
1150    UINT8 nh_result[STREAMS*sizeof(UINT64)];
1151    UINT32 nh_len;
1152    int extra_zeroes_needed;
1153
1154    /* If the message to be hashed is no longer than L1_HASH_LEN, we skip
1155     * the polyhash.
1156     */
1157    if (len <= L1_KEY_LEN) {
1158	if (len == 0)                  /* If zero length messages will not */
1159		nh_len = L1_PAD_BOUNDARY;  /* be seen, comment out this case   */
1160	else
1161		nh_len = ((len + (L1_PAD_BOUNDARY - 1)) & ~(L1_PAD_BOUNDARY - 1));
1162        extra_zeroes_needed = nh_len - len;
1163        zero_pad((UINT8 *)msg + len, extra_zeroes_needed);
1164        nh(&ahc->hash, (UINT8 *)msg, nh_len, len, nh_result);
1165        ip_short(ahc,nh_result, res);
1166    } else {
1167        /* Otherwise, we hash each L1_KEY_LEN chunk with NH, passing the NH
1168         * output to poly_hash().
1169         */
1170        do {
1171            nh(&ahc->hash, (UINT8 *)msg, L1_KEY_LEN, L1_KEY_LEN, nh_result);
1172            poly_hash(ahc,(UINT32 *)nh_result);
1173            len -= L1_KEY_LEN;
1174            msg += L1_KEY_LEN;
1175        } while (len >= L1_KEY_LEN);
1176        if (len) {
1177            nh_len = ((len + (L1_PAD_BOUNDARY - 1)) & ~(L1_PAD_BOUNDARY - 1));
1178            extra_zeroes_needed = nh_len - len;
1179            zero_pad((UINT8 *)msg + len, extra_zeroes_needed);
1180            nh(&ahc->hash, (UINT8 *)msg, nh_len, len, nh_result);
1181            poly_hash(ahc,(UINT32 *)nh_result);
1182        }
1183
1184        ip_long(ahc, res);
1185    }
1186
1187    uhash_reset(ahc);
1188    return 1;
1189}
1190#endif
1191
1192/* ---------------------------------------------------------------------- */
1193/* ---------------------------------------------------------------------- */
1194/* ----- Begin UMAC Section --------------------------------------------- */
1195/* ---------------------------------------------------------------------- */
1196/* ---------------------------------------------------------------------- */
1197
1198/* The UMAC interface has two interfaces, an all-at-once interface where
1199 * the entire message to be authenticated is passed to UMAC in one buffer,
1200 * and a sequential interface where the message is presented a little at a
1201 * time. The all-at-once is more optimized than the sequential version and
1202 * should be preferred when the sequential interface is not required.
1203 */
1204struct umac_ctx {
1205    uhash_ctx hash;          /* Hash function for message compression    */
1206    pdf_ctx pdf;             /* PDF for hashed output                    */
1207    void *free_ptr;          /* Address to free this struct via          */
1208} umac_ctx;
1209
1210/* ---------------------------------------------------------------------- */
1211
1212#if 0
1213int umac_reset(struct umac_ctx *ctx)
1214/* Reset the hash function to begin a new authentication.        */
1215{
1216    uhash_reset(&ctx->hash);
1217    return (1);
1218}
1219#endif
1220
1221/* ---------------------------------------------------------------------- */
1222
1223int umac_delete(struct umac_ctx *ctx)
1224/* Deallocate the ctx structure */
1225{
1226    if (ctx) {
1227        if (ALLOC_BOUNDARY)
1228            ctx = (struct umac_ctx *)ctx->free_ptr;
1229        freezero(ctx, sizeof(*ctx) + ALLOC_BOUNDARY);
1230    }
1231    return (1);
1232}
1233
1234/* ---------------------------------------------------------------------- */
1235
1236struct umac_ctx *umac_new(const u_char key[])
1237/* Dynamically allocate a umac_ctx struct, initialize variables,
1238 * generate subkeys from key. Align to 16-byte boundary.
1239 */
1240{
1241    struct umac_ctx *ctx, *octx;
1242    size_t bytes_to_add;
1243    aes_int_key prf_key;
1244
1245    octx = ctx = xcalloc(1, sizeof(*ctx) + ALLOC_BOUNDARY);
1246    if (ctx) {
1247        if (ALLOC_BOUNDARY) {
1248            bytes_to_add = ALLOC_BOUNDARY -
1249                              ((ptrdiff_t)ctx & (ALLOC_BOUNDARY - 1));
1250            ctx = (struct umac_ctx *)((u_char *)ctx + bytes_to_add);
1251        }
1252        ctx->free_ptr = octx;
1253        aes_key_setup(key, prf_key);
1254        pdf_init(&ctx->pdf, prf_key);
1255        uhash_init(&ctx->hash, prf_key);
1256        explicit_bzero(prf_key, sizeof(prf_key));
1257    }
1258
1259    return (ctx);
1260}
1261
1262/* ---------------------------------------------------------------------- */
1263
1264int umac_final(struct umac_ctx *ctx, u_char tag[], const u_char nonce[8])
1265/* Incorporate any pending data, pad, and generate tag */
1266{
1267    uhash_final(&ctx->hash, (u_char *)tag);
1268    pdf_gen_xor(&ctx->pdf, (const UINT8 *)nonce, (UINT8 *)tag);
1269
1270    return (1);
1271}
1272
1273/* ---------------------------------------------------------------------- */
1274
1275int umac_update(struct umac_ctx *ctx, const u_char *input, long len)
1276/* Given len bytes of data, we parse it into L1_KEY_LEN chunks and   */
1277/* hash each one, calling the PDF on the hashed output whenever the hash- */
1278/* output buffer is full.                                                 */
1279{
1280    uhash_update(&ctx->hash, input, len);
1281    return (1);
1282}
1283
1284/* ---------------------------------------------------------------------- */
1285
1286#if 0
1287int umac(struct umac_ctx *ctx, u_char *input,
1288         long len, u_char tag[],
1289         u_char nonce[8])
1290/* All-in-one version simply calls umac_update() and umac_final().        */
1291{
1292    uhash(&ctx->hash, input, len, (u_char *)tag);
1293    pdf_gen_xor(&ctx->pdf, (UINT8 *)nonce, (UINT8 *)tag);
1294
1295    return (1);
1296}
1297#endif
1298
1299/* ---------------------------------------------------------------------- */
1300/* ---------------------------------------------------------------------- */
1301/* ----- End UMAC Section ----------------------------------------------- */
1302/* ---------------------------------------------------------------------- */
1303/* ---------------------------------------------------------------------- */
1304