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