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