xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/DNSDigest.c (revision f52943a93040563107b95bccb9db87d9971ef47d)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2002-2011 Apple Inc. All rights reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21 
22 #include "mDNSEmbeddedAPI.h"
23 #include "DNSCommon.h"
24 
25 // Disable certain benign warnings with Microsoft compilers
26 #if (defined(_MSC_VER))
27 // Disable "conditional expression is constant" warning for debug macros.
28 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
29 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
30     #pragma warning(disable:4127)
31 #endif
32 
33 
34 // ***************************************************************************
35 #if COMPILER_LIKES_PRAGMA_MARK
36 #pragma mark - Byte Swapping Functions
37 #endif
38 
39 mDNSlocal mDNSu16 NToH16(mDNSu8 * bytes)
40 {
41     return (mDNSu16)((mDNSu16)bytes[0] << 8 | (mDNSu16)bytes[1]);
42 }
43 
44 mDNSlocal mDNSu32 NToH32(mDNSu8 * bytes)
45 {
46     return (mDNSu32)((mDNSu32) bytes[0] << 24 | (mDNSu32) bytes[1] << 16 | (mDNSu32) bytes[2] << 8 | (mDNSu32)bytes[3]);
47 }
48 
49 // ***************************************************************************
50 #if COMPILER_LIKES_PRAGMA_MARK
51 #pragma mark - MD5 Hash Functions
52 #endif
53 
54 
55 /* The source for the has is derived CommonCrypto files CommonDigest.h, md32_common.h, md5_locl.h, md5_locl.h, and openssl/md5.h.
56  * The following changes have been made to the original sources:
57  *    replaced CC_LONG w/ mDNSu32
58  *    replaced CC_MD5* with MD5*
59  *    replaced CC_LONG w/ mDNSu32, removed conditional #defines from md5.h
60  *    removed extern decls for MD5_Init/Update/Final from CommonDigest.h
61  *    removed APPLE_COMMON_DIGEST specific #defines from md5_locl.h
62  *
63  * Note: machine archetecure specific conditionals from the original sources are turned off, but are left in the code
64  * to aid in platform-specific optimizations and debugging.
65  * Sources originally distributed under the following license headers:
66  * CommonDigest.h - APSL
67  *
68  * md32_Common.h
69  * ====================================================================
70  * Copyright (c) 1999-2002 The OpenSSL Project.  All rights reserved.
71  *
72  * Redistribution and use in source and binary forms, with or without
73  * modification, are permitted provided that the following conditions
74  * are met:
75  *
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  *
79  * 2. Redistributions in binary form must reproduce the above copyright
80  *    notice, this list of conditions and the following disclaimer in
81  *    the documentation and/or other materials provided with the
82  *    distribution.
83  *
84  * 3. All advertising materials mentioning features or use of this
85  *    software must display the following acknowledgment:
86  *    "This product includes software developed by the OpenSSL Project
87  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
88  *
89  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
90  *    endorse or promote products derived from this software without
91  *    prior written permission. For written permission, please contact
92  *    licensing@OpenSSL.org.
93  *
94  * 5. Products derived from this software may not be called "OpenSSL"
95  *    nor may "OpenSSL" appear in their names without prior written
96  *    permission of the OpenSSL Project.
97  *
98  * 6. Redistributions of any form whatsoever must retain the following
99  *    acknowledgment:
100  *    "This product includes software developed by the OpenSSL Project
101  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
102  *
103  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
104  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
105  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
106  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
107  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
108  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
109  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
110  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
111  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
112  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
113  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
114  * OF THE POSSIBILITY OF SUCH DAMAGE.
115  *
116  *
117  * md5_dgst.c, md5_locl.h
118  * ====================================================================
119  *
120  * This product includes cryptographic software written by Eric Young
121  * (eay@cryptsoft.com).  This product includes software written by Tim
122  * Hudson (tjh@cryptsoft.com).
123  *
124  * Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
125  * All rights reserved.
126  *
127  * This package is an SSL implementation written
128  * by Eric Young (eay@cryptsoft.com).
129  * The implementation was written so as to conform with Netscapes SSL.
130  *
131  * This library is free for commercial and non-commercial use as long as
132  * the following conditions are aheared to.  The following conditions
133  * apply to all code found in this distribution, be it the RC4, RSA,
134  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
135  * included with this distribution is covered by the same copyright terms
136  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
137  *
138  * Copyright remains Eric Young's, and as such any Copyright notices in
139  * the code are not to be removed.
140  * If this package is used in a product, Eric Young should be given attribution
141  * as the author of the parts of the library used.
142  * This can be in the form of a textual message at program startup or
143  * in documentation (online or textual) provided with the package.
144  *
145  * Redistribution and use in source and binary forms, with or without
146  * modification, are permitted provided that the following conditions
147  * are met:
148  * 1. Redistributions of source code must retain the copyright
149  *    notice, this list of conditions and the following disclaimer.
150  * 2. Redistributions in binary form must reproduce the above copyright
151  *    notice, this list of conditions and the following disclaimer in the
152  *    documentation and/or other materials provided with the distribution.
153  * 3. All advertising materials mentioning features or use of this software
154  *    must display the following acknowledgement:
155  *    "This product includes cryptographic software written by
156  *     Eric Young (eay@cryptsoft.com)"
157  *    The word 'cryptographic' can be left out if the rouines from the library
158  *    being used are not cryptographic related :-).
159  * 4. If you include any Windows specific code (or a derivative thereof) from
160  *    the apps directory (application code) you must include an acknowledgement:
161  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
162  *
163  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
164  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
165  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
166  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
167  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
168  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
169  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
170  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
171  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
172  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
173  * SUCH DAMAGE.
174  *
175  * The licence and distribution terms for any publically available version or
176  * derivative of this code cannot be changed.  i.e. this code cannot simply be
177  * copied and put under another distribution licence
178  * [including the GNU Public Licence.]
179  *
180  */
181 
182 //from CommonDigest.h
183 
184 
185 
186 // from openssl/md5.h
187 
188 #define MD5_CBLOCK  64
189 #define MD5_LBLOCK  (MD5_CBLOCK/4)
190 #define MD5_DIGEST_LENGTH 16
191 
192 void MD5_Transform(MD5_CTX *c, const unsigned char *b);
193 
194 // From md5_locl.h
195 
196 #ifndef MD5_LONG_LOG2
197 #define MD5_LONG_LOG2 2 /* default to 32 bits */
198 #endif
199 
200 #ifdef MD5_ASM
201 # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__)
202 #  define md5_block_host_order md5_block_asm_host_order
203 # elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
204 void md5_block_asm_data_order_aligned (MD5_CTX *c, const mDNSu32 *p,int num);
205 #  define HASH_BLOCK_DATA_ORDER_ALIGNED md5_block_asm_data_order_aligned
206 # endif
207 #endif
208 
209 void md5_block_host_order (MD5_CTX *c, const void *p,int num);
210 void md5_block_data_order (MD5_CTX *c, const void *p,int num);
211 
212 #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__)
213 /*
214  * *_block_host_order is expected to handle aligned data while
215  * *_block_data_order - unaligned. As algorithm and host (x86)
216  * are in this case of the same "endianness" these two are
217  * otherwise indistinguishable. But normally you don't want to
218  * call the same function because unaligned access in places
219  * where alignment is expected is usually a "Bad Thing". Indeed,
220  * on RISCs you get punished with BUS ERROR signal or *severe*
221  * performance degradation. Intel CPUs are in turn perfectly
222  * capable of loading unaligned data without such drastic side
223  * effect. Yes, they say it's slower than aligned load, but no
224  * exception is generated and therefore performance degradation
225  * is *incomparable* with RISCs. What we should weight here is
226  * costs of unaligned access against costs of aligning data.
227  * According to my measurements allowing unaligned access results
228  * in ~9% performance improvement on Pentium II operating at
229  * 266MHz. I won't be surprised if the difference will be higher
230  * on faster systems:-)
231  *
232  *				<appro@fy.chalmers.se>
233  */
234 #define md5_block_data_order md5_block_host_order
235 #endif
236 
237 #define DATA_ORDER_IS_LITTLE_ENDIAN
238 
239 #define HASH_LONG       mDNSu32
240 #define HASH_LONG_LOG2  MD5_LONG_LOG2
241 #define HASH_CTX        MD5_CTX
242 #define HASH_CBLOCK     MD5_CBLOCK
243 #define HASH_LBLOCK     MD5_LBLOCK
244 
245 #define HASH_UPDATE     MD5_Update
246 #define HASH_TRANSFORM  MD5_Transform
247 #define HASH_FINAL      MD5_Final
248 
249 #define HASH_MAKE_STRING(c,s)   do {    \
250         unsigned long ll;       \
251         ll=(c)->A; HOST_l2c(ll,(s));    \
252         ll=(c)->B; HOST_l2c(ll,(s));    \
253         ll=(c)->C; HOST_l2c(ll,(s));    \
254         ll=(c)->D; HOST_l2c(ll,(s));    \
255 } while (0)
256 #define HASH_BLOCK_HOST_ORDER   md5_block_host_order
257 #if !defined(L_ENDIAN) || defined(md5_block_data_order)
258 #define HASH_BLOCK_DATA_ORDER   md5_block_data_order
259 /*
260  * Little-endians (Intel and Alpha) feel better without this.
261  * It looks like memcpy does better job than generic
262  * md5_block_data_order on copying-n-aligning input data.
263  * But frankly speaking I didn't expect such result on Alpha.
264  * On the other hand I've got this with egcs-1.0.2 and if
265  * program is compiled with another (better?) compiler it
266  * might turn out other way around.
267  *
268  *				<appro@fy.chalmers.se>
269  */
270 #endif
271 
272 
273 // from md32_common.h
274 
275 /*
276  * This is a generic 32 bit "collector" for message digest algorithms.
277  * Whenever needed it collects input character stream into chunks of
278  * 32 bit values and invokes a block function that performs actual hash
279  * calculations.
280  *
281  * Porting guide.
282  *
283  * Obligatory macros:
284  *
285  * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
286  *	this macro defines byte order of input stream.
287  * HASH_CBLOCK
288  *	size of a unit chunk HASH_BLOCK operates on.
289  * HASH_LONG
290  *	has to be at lest 32 bit wide, if it's wider, then
291  *	HASH_LONG_LOG2 *has to* be defined along
292  * HASH_CTX
293  *	context structure that at least contains following
294  *	members:
295  *		typedef struct {
296  *			...
297  *			HASH_LONG	Nl,Nh;
298  *			HASH_LONG	data[HASH_LBLOCK];
299  *			int		num;
300  *			...
301  *			} HASH_CTX;
302  * HASH_UPDATE
303  *	name of "Update" function, implemented here.
304  * HASH_TRANSFORM
305  *	name of "Transform" function, implemented here.
306  * HASH_FINAL
307  *	name of "Final" function, implemented here.
308  * HASH_BLOCK_HOST_ORDER
309  *	name of "block" function treating *aligned* input message
310  *	in host byte order, implemented externally.
311  * HASH_BLOCK_DATA_ORDER
312  *	name of "block" function treating *unaligned* input message
313  *	in original (data) byte order, implemented externally (it
314  *	actually is optional if data and host are of the same
315  *	"endianess").
316  * HASH_MAKE_STRING
317  *	macro convering context variables to an ASCII hash string.
318  *
319  * Optional macros:
320  *
321  * B_ENDIAN or L_ENDIAN
322  *	defines host byte-order.
323  * HASH_LONG_LOG2
324  *	defaults to 2 if not states otherwise.
325  * HASH_LBLOCK
326  *	assumed to be HASH_CBLOCK/4 if not stated otherwise.
327  * HASH_BLOCK_DATA_ORDER_ALIGNED
328  *	alternative "block" function capable of treating
329  *	aligned input message in original (data) order,
330  *	implemented externally.
331  *
332  * MD5 example:
333  *
334  *	#define DATA_ORDER_IS_LITTLE_ENDIAN
335  *
336  *	#define HASH_LONG		mDNSu32
337  *	#define HASH_LONG_LOG2	mDNSu32_LOG2
338  *	#define HASH_CTX		MD5_CTX
339  *	#define HASH_CBLOCK		MD5_CBLOCK
340  *	#define HASH_LBLOCK		MD5_LBLOCK
341  *	#define HASH_UPDATE		MD5_Update
342  *	#define HASH_TRANSFORM		MD5_Transform
343  *	#define HASH_FINAL		MD5_Final
344  *	#define HASH_BLOCK_HOST_ORDER	md5_block_host_order
345  *	#define HASH_BLOCK_DATA_ORDER	md5_block_data_order
346  *
347  *					<appro@fy.chalmers.se>
348  */
349 
350 #if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
351 #error "DATA_ORDER must be defined!"
352 #endif
353 
354 #ifndef HASH_CBLOCK
355 #error "HASH_CBLOCK must be defined!"
356 #endif
357 #ifndef HASH_LONG
358 #error "HASH_LONG must be defined!"
359 #endif
360 #ifndef HASH_CTX
361 #error "HASH_CTX must be defined!"
362 #endif
363 
364 #ifndef HASH_UPDATE
365 #error "HASH_UPDATE must be defined!"
366 #endif
367 #ifndef HASH_TRANSFORM
368 #error "HASH_TRANSFORM must be defined!"
369 #endif
370 #ifndef HASH_FINAL
371 #error "HASH_FINAL must be defined!"
372 #endif
373 
374 #ifndef HASH_BLOCK_HOST_ORDER
375 #error "HASH_BLOCK_HOST_ORDER must be defined!"
376 #endif
377 
378 #if 0
379 /*
380  * Moved below as it's required only if HASH_BLOCK_DATA_ORDER_ALIGNED
381  * isn't defined.
382  */
383 #ifndef HASH_BLOCK_DATA_ORDER
384 #error "HASH_BLOCK_DATA_ORDER must be defined!"
385 #endif
386 #endif
387 
388 #ifndef HASH_LBLOCK
389 #define HASH_LBLOCK (HASH_CBLOCK/4)
390 #endif
391 
392 #ifndef HASH_LONG_LOG2
393 #define HASH_LONG_LOG2  2
394 #endif
395 
396 /*
397  * Engage compiler specific rotate intrinsic function if available.
398  */
399 #undef ROTATE
400 #ifndef PEDANTIC
401 # if 0 /* defined(_MSC_VER) */
402 #  define ROTATE(a,n)   _lrotl(a,n)
403 # elif defined(__MWERKS__)
404 #  if defined(__POWERPC__)
405 #   define ROTATE(a,n)  (unsigned MD32_REG_T)__rlwinm((int)a,n,0,31)
406 #  elif defined(__MC68K__)
407 /* Motorola specific tweak. <appro@fy.chalmers.se> */
408 #   define ROTATE(a,n)  (n<24 ? __rol(a,n) : __ror(a,32-n))
409 #  else
410 #   define ROTATE(a,n)  __rol(a,n)
411 #  endif
412 # elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
413 /*
414  * Some GNU C inline assembler templates. Note that these are
415  * rotates by *constant* number of bits! But that's exactly
416  * what we need here...
417  *
418  *                  <appro@fy.chalmers.se>
419  */
420 /*
421  * LLVM is more strict about compatibility of types between input & output constraints,
422  * but we want these to be rotations of 32 bits, not 64, so we explicitly drop the
423  * most significant bytes by casting to an unsigned int.
424  */
425 #  if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
426 #   define ROTATE(a,n)  ({ register unsigned int ret;   \
427                            asm (           \
428                                "roll %1,%0"        \
429                                : "=r" (ret)     \
430                                : "I" (n), "0" ((unsigned int)a)  \
431                                : "cc");        \
432                            ret;             \
433                          })
434 #  elif defined(__powerpc) || defined(__ppc)
435 #   define ROTATE(a,n)  ({ register unsigned int ret;   \
436                            asm (           \
437                                "rlwinm %0,%1,%2,0,31"  \
438                                : "=r" (ret)     \
439                                : "r" (a), "I" (n));  \
440                            ret;             \
441                          })
442 #  endif
443 # endif
444 
445 /*
446  * Engage compiler specific "fetch in reverse byte order"
447  * intrinsic function if available.
448  */
449 # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
450 /* some GNU C inline assembler templates by <appro@fy.chalmers.se> */
451 #  if (defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)) && !defined(I386_ONLY)
452 #   define BE_FETCH32(a)    ({ register unsigned int l=(a); \
453                                asm (           \
454                                    "bswapl %0"     \
455                                    : "=r" (l) : "0" (l));    \
456                                l;                \
457                              })
458 #  elif defined(__powerpc)
459 #   define LE_FETCH32(a)    ({ register unsigned int l; \
460                                asm (           \
461                                    "lwbrx %0,0,%1"     \
462                                    : "=r" (l)       \
463                                    : "r" (a));      \
464                                l;               \
465                              })
466 
467 #  elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
468 #  define LE_FETCH32(a) ({ register unsigned int l;     \
469                            asm (               \
470                                "lda [%1]#ASI_PRIMARY_LITTLE,%0" \
471                                : "=r" (l)           \
472                                : "r" (a));          \
473                            l;                   \
474                          })
475 #  endif
476 # endif
477 #endif /* PEDANTIC */
478 
479 #if HASH_LONG_LOG2==2   /* Engage only if sizeof(HASH_LONG)== 4 */
480 /* A nice byte order reversal from Wei Dai <weidai@eskimo.com> */
481 #ifdef ROTATE
482 /* 5 instructions with rotate instruction, else 9 */
483 #define REVERSE_FETCH32(a,l)    (                   \
484         l=*(const HASH_LONG *)(a),              \
485         ((ROTATE(l,8)&0x00FF00FF)|(ROTATE((l&0x00FF00FF),24)))  \
486         )
487 #else
488 /* 6 instructions with rotate instruction, else 8 */
489 #define REVERSE_FETCH32(a,l)    (               \
490         l=*(const HASH_LONG *)(a),          \
491         l=(((l>>8)&0x00FF00FF)|((l&0x00FF00FF)<<8)),    \
492         ROTATE(l,16)                    \
493         )
494 /*
495  * Originally the middle line started with l=(((l&0xFF00FF00)>>8)|...
496  * It's rewritten as above for two reasons:
497  *	- RISCs aren't good at long constants and have to explicitely
498  *	  compose 'em with several (well, usually 2) instructions in a
499  *	  register before performing the actual operation and (as you
500  *	  already realized:-) having same constant should inspire the
501  *	  compiler to permanently allocate the only register for it;
502  *	- most modern CPUs have two ALUs, but usually only one has
503  *	  circuitry for shifts:-( this minor tweak inspires compiler
504  *	  to schedule shift instructions in a better way...
505  *
506  *				<appro@fy.chalmers.se>
507  */
508 #endif
509 #endif
510 
511 #ifndef ROTATE
512 #define ROTATE(a,n)     (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
513 #endif
514 
515 /*
516  * Make some obvious choices. E.g., HASH_BLOCK_DATA_ORDER_ALIGNED
517  * and HASH_BLOCK_HOST_ORDER ought to be the same if input data
518  * and host are of the same "endianess". It's possible to mask
519  * this with blank #define HASH_BLOCK_DATA_ORDER though...
520  *
521  *				<appro@fy.chalmers.se>
522  */
523 #if defined(B_ENDIAN)
524 #  if defined(DATA_ORDER_IS_BIG_ENDIAN)
525 #    if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
526 #      define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER
527 #    endif
528 #  elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
529 #    ifndef HOST_FETCH32
530 #      ifdef LE_FETCH32
531 #        define HOST_FETCH32(p,l)   LE_FETCH32(p)
532 #      elif defined(REVERSE_FETCH32)
533 #        define HOST_FETCH32(p,l)   REVERSE_FETCH32(p,l)
534 #      endif
535 #    endif
536 #  endif
537 #elif defined(L_ENDIAN)
538 #  if defined(DATA_ORDER_IS_LITTLE_ENDIAN)
539 #    if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
540 #      define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER
541 #    endif
542 #  elif defined(DATA_ORDER_IS_BIG_ENDIAN)
543 #    ifndef HOST_FETCH32
544 #      ifdef BE_FETCH32
545 #        define HOST_FETCH32(p,l)   BE_FETCH32(p)
546 #      elif defined(REVERSE_FETCH32)
547 #        define HOST_FETCH32(p,l)   REVERSE_FETCH32(p,l)
548 #      endif
549 #    endif
550 #  endif
551 #endif
552 
553 #if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
554 #ifndef HASH_BLOCK_DATA_ORDER
555 #error "HASH_BLOCK_DATA_ORDER must be defined!"
556 #endif
557 #endif
558 
559 // None of the invocations of the following macros actually use the result,
560 // so cast them to void to avoid any compiler warnings/errors about not using
561 // the result (e.g. when using clang).
562 // If the resultant values need to be used at some point, these must be changed.
563 #define HOST_c2l(c,l) ((void)_HOST_c2l(c,l))
564 #define HOST_l2c(l,c) ((void)_HOST_l2c(l,c))
565 
566 #if defined(DATA_ORDER_IS_BIG_ENDIAN)
567 
568 #define _HOST_c2l(c,l)  (l =(((unsigned long)(*((c)++)))<<24),      \
569                          l|=(((unsigned long)(*((c)++)))<<16),      \
570                          l|=(((unsigned long)(*((c)++)))<< 8),      \
571                          l|=(((unsigned long)(*((c)++)))    ),      \
572                          l)
573 #define HOST_p_c2l(c,l,n)   {                   \
574         switch (n) {                    \
575         case 0: l =((unsigned long)(*((c)++)))<<24; \
576         case 1: l|=((unsigned long)(*((c)++)))<<16; \
577         case 2: l|=((unsigned long)(*((c)++)))<< 8; \
578         case 3: l|=((unsigned long)(*((c)++)));     \
579         } }
580 #define HOST_p_c2l_p(c,l,sc,len) {                  \
581         switch (sc) {                   \
582         case 0: l =((unsigned long)(*((c)++)))<<24; \
583             if (--len == 0) break;                                                 \
584         case 1: l|=((unsigned long)(*((c)++)))<<16; \
585             if (--len == 0) break;                                                 \
586         case 2: l|=((unsigned long)(*((c)++)))<< 8; \
587         } }
588 /* NOTE the pointer is not incremented at the end of this */
589 #define HOST_c2l_p(c,l,n)   {                   \
590         l=0; (c)+=n;                    \
591         switch (n) {                    \
592         case 3: l =((unsigned long)(*(--(c))))<< 8; \
593         case 2: l|=((unsigned long)(*(--(c))))<<16; \
594         case 1: l|=((unsigned long)(*(--(c))))<<24; \
595         } }
596 #define _HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)>>24)&0xff),  \
597                          *((c)++)=(unsigned char)(((l)>>16)&0xff),  \
598                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),  \
599                          *((c)++)=(unsigned char)(((l)    )&0xff),  \
600                          l)
601 
602 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
603 
604 #define _HOST_c2l(c,l)  (l =(((unsigned long)(*((c)++)))    ),      \
605                          l|=(((unsigned long)(*((c)++)))<< 8),      \
606                          l|=(((unsigned long)(*((c)++)))<<16),      \
607                          l|=(((unsigned long)(*((c)++)))<<24),      \
608                          l)
609 #define HOST_p_c2l(c,l,n)   {                   \
610         switch (n) {                    \
611         case 0: l =((unsigned long)(*((c)++)));     \
612 	/* FALLTHROUGH */	\
613         case 1: l|=((unsigned long)(*((c)++)))<< 8; \
614 	/* FALLTHROUGH */	\
615         case 2: l|=((unsigned long)(*((c)++)))<<16; \
616 	/* FALLTHROUGH */	\
617         case 3: l|=((unsigned long)(*((c)++)))<<24; \
618         } }
619 #define HOST_p_c2l_p(c,l,sc,len) {                  \
620         switch (sc) {                   \
621         case 0: l =((unsigned long)(*((c)++)));     \
622             if (--len == 0) break;                                                 \
623 	/* FALLTHROUGH */	\
624         case 1: l|=((unsigned long)(*((c)++)))<< 8; \
625             if (--len == 0) break;                                                 \
626 	/* FALLTHROUGH */	\
627         case 2: l|=((unsigned long)(*((c)++)))<<16; \
628         } }
629 /* NOTE the pointer is not incremented at the end of this */
630 #define HOST_c2l_p(c,l,n)   {                   \
631         l=0; (c)+=n;                    \
632         switch (n) {                    \
633         case 3: l =((unsigned long)(*(--(c))))<<16; \
634 	/* FALLTHROUGH */	\
635         case 2: l|=((unsigned long)(*(--(c))))<< 8; \
636 	/* FALLTHROUGH */	\
637         case 1: l|=((unsigned long)(*(--(c))));     \
638         } }
639 #define _HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)    )&0xff),  \
640                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),  \
641                          *((c)++)=(unsigned char)(((l)>>16)&0xff),  \
642                          *((c)++)=(unsigned char)(((l)>>24)&0xff),  \
643                          l)
644 
645 #endif
646 
647 /*
648  * Time for some action:-)
649  */
650 
651 int HASH_UPDATE (HASH_CTX *c, const void *data_, unsigned long len)
652 {
653     const unsigned char *data=(const unsigned char *)data_;
654     register HASH_LONG * p;
655     register unsigned long l;
656     int sw,sc,ew,ec;
657 
658     if (len==0) return 1;
659 
660     l=(c->Nl+(len<<3))&0xffffffffL;
661     /* 95-05-24 eay Fixed a bug with the overflow handling, thanks to
662      * Wei Dai <weidai@eskimo.com> for pointing it out. */
663     if (l < c->Nl) /* overflow */
664         c->Nh++;
665     c->Nh+=(len>>29);
666     c->Nl=l;
667 
668     if (c->num != 0)
669     {
670         p=c->data;
671         sw=c->num>>2;
672         sc=c->num&0x03;
673 
674         if ((c->num+len) >= HASH_CBLOCK)
675         {
676             l=p[sw]; HOST_p_c2l(data,l,sc); p[sw++]=l;
677             for (; sw<HASH_LBLOCK; sw++)
678             {
679                 HOST_c2l(data,l); p[sw]=l;
680             }
681             HASH_BLOCK_HOST_ORDER (c,p,1);
682             len-=(HASH_CBLOCK-c->num);
683             c->num=0;
684             /* drop through and do the rest */
685         }
686         else
687         {
688             c->num+=len;
689             if ((sc+len) < 4) /* ugly, add char's to a word */
690             {
691                 l=p[sw]; HOST_p_c2l_p(data,l,sc,len); p[sw]=l;
692             }
693             else
694             {
695                 ew=(c->num>>2);
696                 ec=(c->num&0x03);
697                 if (sc)
698                     l=p[sw];
699                 HOST_p_c2l(data,l,sc);
700                 p[sw++]=l;
701                 for (; sw < ew; sw++)
702                 {
703                     HOST_c2l(data,l); p[sw]=l;
704                 }
705                 if (ec)
706                 {
707                     HOST_c2l_p(data,l,ec); p[sw]=l;
708                 }
709             }
710             return 1;
711         }
712     }
713 
714     sw=(int)(len/HASH_CBLOCK);
715     if (sw > 0)
716     {
717 #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
718         /*
719          * Note that HASH_BLOCK_DATA_ORDER_ALIGNED gets defined
720          * only if sizeof(HASH_LONG)==4.
721          */
722         if ((((unsigned long)data)%4) == 0)
723         {
724             /* data is properly aligned so that we can cast it: */
725             HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,sw);
726             sw*=HASH_CBLOCK;
727             data+=sw;
728             len-=sw;
729         }
730         else
731 #if !defined(HASH_BLOCK_DATA_ORDER)
732             while (sw--)
733             {
734                 mDNSPlatformMemCopy(p=c->data,data,HASH_CBLOCK);
735                 HASH_BLOCK_DATA_ORDER_ALIGNED(c,p,1);
736                 data+=HASH_CBLOCK;
737                 len-=HASH_CBLOCK;
738             }
739 #endif
740 #endif
741 #if defined(HASH_BLOCK_DATA_ORDER)
742         {
743             HASH_BLOCK_DATA_ORDER(c,data,sw);
744             sw*=HASH_CBLOCK;
745             data+=sw;
746             len-=sw;
747         }
748 #endif
749     }
750 
751     if (len!=0)
752     {
753         p = c->data;
754         c->num = (int)len;
755         ew=(int)(len>>2);   /* words to copy */
756         ec=(int)(len&0x03);
757         for (; ew; ew--,p++)
758         {
759             HOST_c2l(data,l); *p=l;
760         }
761         HOST_c2l_p(data,l,ec);
762         *p=l;
763     }
764     return 1;
765 }
766 
767 
768 void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data)
769 {
770 #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
771     if ((((unsigned long)data)%4) == 0)
772         /* data is properly aligned so that we can cast it: */
773         HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,1);
774     else
775 #if !defined(HASH_BLOCK_DATA_ORDER)
776     {
777         mDNSPlatformMemCopy(c->data,data,HASH_CBLOCK);
778         HASH_BLOCK_DATA_ORDER_ALIGNED (c,c->data,1);
779     }
780 #endif
781 #endif
782 #if defined(HASH_BLOCK_DATA_ORDER)
783     HASH_BLOCK_DATA_ORDER (c,data,1);
784 #endif
785 }
786 
787 
788 int HASH_FINAL (unsigned char *md, HASH_CTX *c)
789 {
790     register HASH_LONG *p;
791     register unsigned long l;
792     register int i,j;
793     static const unsigned char end[4]={0x80,0x00,0x00,0x00};
794     const unsigned char *cp=end;
795 
796     /* c->num should definitly have room for at least one more byte. */
797     p=c->data;
798     i=c->num>>2;
799     j=c->num&0x03;
800 
801 #if 0
802     /* purify often complains about the following line as an
803      * Uninitialized Memory Read.  While this can be true, the
804      * following p_c2l macro will reset l when that case is true.
805      * This is because j&0x03 contains the number of 'valid' bytes
806      * already in p[i].  If and only if j&0x03 == 0, the UMR will
807      * occur but this is also the only time p_c2l will do
808      * l= *(cp++) instead of l|= *(cp++)
809      * Many thanks to Alex Tang <altitude@cic.net> for pickup this
810      * 'potential bug' */
811 #ifdef PURIFY
812     if (j==0) p[i]=0; /* Yeah, but that's not the way to fix it:-) */
813 #endif
814     l=p[i];
815 #else
816     l = (j==0) ? 0 : p[i];
817 #endif
818     HOST_p_c2l(cp,l,j); p[i++]=l; /* i is the next 'undefined word' */
819 
820     if (i>(HASH_LBLOCK-2)) /* save room for Nl and Nh */
821     {
822         if (i<HASH_LBLOCK) p[i]=0;
823         HASH_BLOCK_HOST_ORDER (c,p,1);
824         i=0;
825     }
826     for (; i<(HASH_LBLOCK-2); i++)
827         p[i]=0;
828 
829 #if   defined(DATA_ORDER_IS_BIG_ENDIAN)
830     p[HASH_LBLOCK-2]=c->Nh;
831     p[HASH_LBLOCK-1]=c->Nl;
832 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
833     p[HASH_LBLOCK-2]=c->Nl;
834     p[HASH_LBLOCK-1]=c->Nh;
835 #endif
836     HASH_BLOCK_HOST_ORDER (c,p,1);
837 
838 #ifndef HASH_MAKE_STRING
839 #error "HASH_MAKE_STRING must be defined!"
840 #else
841     HASH_MAKE_STRING(c,md);
842 #endif
843 
844     c->num=0;
845     /* clear stuff, HASH_BLOCK may be leaving some stuff on the stack
846      * but I'm not worried :-)
847        OPENSSL_cleanse((void *)c,sizeof(HASH_CTX));
848      */
849     return 1;
850 }
851 
852 #ifndef MD32_REG_T
853 #define MD32_REG_T long
854 /*
855  * This comment was originaly written for MD5, which is why it
856  * discusses A-D. But it basically applies to all 32-bit digests,
857  * which is why it was moved to common header file.
858  *
859  * In case you wonder why A-D are declared as long and not
860  * as mDNSu32. Doing so results in slight performance
861  * boost on LP64 architectures. The catch is we don't
862  * really care if 32 MSBs of a 64-bit register get polluted
863  * with eventual overflows as we *save* only 32 LSBs in
864  * *either* case. Now declaring 'em long excuses the compiler
865  * from keeping 32 MSBs zeroed resulting in 13% performance
866  * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
867  * Well, to be honest it should say that this *prevents*
868  * performance degradation.
869  *				<appro@fy.chalmers.se>
870  * Apparently there're LP64 compilers that generate better
871  * code if A-D are declared int. Most notably GCC-x86_64
872  * generates better code.
873  *				<appro@fy.chalmers.se>
874  */
875 #endif
876 
877 
878 // from md5_locl.h (continued)
879 
880 /*
881  #define	F(x,y,z)	(((x) & (y))  |  ((~(x)) & (z)))
882  #define	G(x,y,z)	(((x) & (z))  |  ((y) & (~(z))))
883  */
884 
885 /* As pointed out by Wei Dai <weidai@eskimo.com>, the above can be
886  * simplified to the code below.  Wei attributes these optimizations
887  * to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
888  */
889 #define F(b,c,d)    ((((c) ^ (d)) & (b)) ^ (d))
890 #define G(b,c,d)    ((((b) ^ (c)) & (d)) ^ (c))
891 #define H(b,c,d)    ((b) ^ (c) ^ (d))
892 #define I(b,c,d)    (((~(d)) | (b)) ^ (c))
893 
894 #define R0(a,b,c,d,k,s,t) { \
895         a+=((k)+(t)+F((b),(c),(d))); \
896         a=ROTATE(a,s); \
897         a+=b; }; \
898 
899 #define R1(a,b,c,d,k,s,t) { \
900         a+=((k)+(t)+G((b),(c),(d))); \
901         a=ROTATE(a,s); \
902         a+=b; };
903 
904 #define R2(a,b,c,d,k,s,t) { \
905         a+=((k)+(t)+H((b),(c),(d))); \
906         a=ROTATE(a,s); \
907         a+=b; };
908 
909 #define R3(a,b,c,d,k,s,t) { \
910         a+=((k)+(t)+I((b),(c),(d))); \
911         a=ROTATE(a,s); \
912         a+=b; };
913 
914 // from md5_dgst.c
915 
916 
917 /* Implemented from RFC1321 The MD5 Message-Digest Algorithm
918  */
919 
920 #define INIT_DATA_A (unsigned long)0x67452301L
921 #define INIT_DATA_B (unsigned long)0xefcdab89L
922 #define INIT_DATA_C (unsigned long)0x98badcfeL
923 #define INIT_DATA_D (unsigned long)0x10325476L
924 
925 int MD5_Init(MD5_CTX *c)
926 {
927     c->A=INIT_DATA_A;
928     c->B=INIT_DATA_B;
929     c->C=INIT_DATA_C;
930     c->D=INIT_DATA_D;
931     c->Nl=0;
932     c->Nh=0;
933     c->num=0;
934     return 1;
935 }
936 
937 #ifndef md5_block_host_order
938 void md5_block_host_order (MD5_CTX *c, const void *data, int num)
939 {
940     const mDNSu32 *X=(const mDNSu32 *)data;
941     register unsigned MD32_REG_T A,B,C,D;
942 
943     A=c->A;
944     B=c->B;
945     C=c->C;
946     D=c->D;
947 
948     for (; num--; X+=HASH_LBLOCK)
949     {
950         /* Round 0 */
951         R0(A,B,C,D,X[ 0], 7,0xd76aa478L);
952         R0(D,A,B,C,X[ 1],12,0xe8c7b756L);
953         R0(C,D,A,B,X[ 2],17,0x242070dbL);
954         R0(B,C,D,A,X[ 3],22,0xc1bdceeeL);
955         R0(A,B,C,D,X[ 4], 7,0xf57c0fafL);
956         R0(D,A,B,C,X[ 5],12,0x4787c62aL);
957         R0(C,D,A,B,X[ 6],17,0xa8304613L);
958         R0(B,C,D,A,X[ 7],22,0xfd469501L);
959         R0(A,B,C,D,X[ 8], 7,0x698098d8L);
960         R0(D,A,B,C,X[ 9],12,0x8b44f7afL);
961         R0(C,D,A,B,X[10],17,0xffff5bb1L);
962         R0(B,C,D,A,X[11],22,0x895cd7beL);
963         R0(A,B,C,D,X[12], 7,0x6b901122L);
964         R0(D,A,B,C,X[13],12,0xfd987193L);
965         R0(C,D,A,B,X[14],17,0xa679438eL);
966         R0(B,C,D,A,X[15],22,0x49b40821L);
967         /* Round 1 */
968         R1(A,B,C,D,X[ 1], 5,0xf61e2562L);
969         R1(D,A,B,C,X[ 6], 9,0xc040b340L);
970         R1(C,D,A,B,X[11],14,0x265e5a51L);
971         R1(B,C,D,A,X[ 0],20,0xe9b6c7aaL);
972         R1(A,B,C,D,X[ 5], 5,0xd62f105dL);
973         R1(D,A,B,C,X[10], 9,0x02441453L);
974         R1(C,D,A,B,X[15],14,0xd8a1e681L);
975         R1(B,C,D,A,X[ 4],20,0xe7d3fbc8L);
976         R1(A,B,C,D,X[ 9], 5,0x21e1cde6L);
977         R1(D,A,B,C,X[14], 9,0xc33707d6L);
978         R1(C,D,A,B,X[ 3],14,0xf4d50d87L);
979         R1(B,C,D,A,X[ 8],20,0x455a14edL);
980         R1(A,B,C,D,X[13], 5,0xa9e3e905L);
981         R1(D,A,B,C,X[ 2], 9,0xfcefa3f8L);
982         R1(C,D,A,B,X[ 7],14,0x676f02d9L);
983         R1(B,C,D,A,X[12],20,0x8d2a4c8aL);
984         /* Round 2 */
985         R2(A,B,C,D,X[ 5], 4,0xfffa3942L);
986         R2(D,A,B,C,X[ 8],11,0x8771f681L);
987         R2(C,D,A,B,X[11],16,0x6d9d6122L);
988         R2(B,C,D,A,X[14],23,0xfde5380cL);
989         R2(A,B,C,D,X[ 1], 4,0xa4beea44L);
990         R2(D,A,B,C,X[ 4],11,0x4bdecfa9L);
991         R2(C,D,A,B,X[ 7],16,0xf6bb4b60L);
992         R2(B,C,D,A,X[10],23,0xbebfbc70L);
993         R2(A,B,C,D,X[13], 4,0x289b7ec6L);
994         R2(D,A,B,C,X[ 0],11,0xeaa127faL);
995         R2(C,D,A,B,X[ 3],16,0xd4ef3085L);
996         R2(B,C,D,A,X[ 6],23,0x04881d05L);
997         R2(A,B,C,D,X[ 9], 4,0xd9d4d039L);
998         R2(D,A,B,C,X[12],11,0xe6db99e5L);
999         R2(C,D,A,B,X[15],16,0x1fa27cf8L);
1000         R2(B,C,D,A,X[ 2],23,0xc4ac5665L);
1001         /* Round 3 */
1002         R3(A,B,C,D,X[ 0], 6,0xf4292244L);
1003         R3(D,A,B,C,X[ 7],10,0x432aff97L);
1004         R3(C,D,A,B,X[14],15,0xab9423a7L);
1005         R3(B,C,D,A,X[ 5],21,0xfc93a039L);
1006         R3(A,B,C,D,X[12], 6,0x655b59c3L);
1007         R3(D,A,B,C,X[ 3],10,0x8f0ccc92L);
1008         R3(C,D,A,B,X[10],15,0xffeff47dL);
1009         R3(B,C,D,A,X[ 1],21,0x85845dd1L);
1010         R3(A,B,C,D,X[ 8], 6,0x6fa87e4fL);
1011         R3(D,A,B,C,X[15],10,0xfe2ce6e0L);
1012         R3(C,D,A,B,X[ 6],15,0xa3014314L);
1013         R3(B,C,D,A,X[13],21,0x4e0811a1L);
1014         R3(A,B,C,D,X[ 4], 6,0xf7537e82L);
1015         R3(D,A,B,C,X[11],10,0xbd3af235L);
1016         R3(C,D,A,B,X[ 2],15,0x2ad7d2bbL);
1017         R3(B,C,D,A,X[ 9],21,0xeb86d391L);
1018 
1019         A = c->A += A;
1020         B = c->B += B;
1021         C = c->C += C;
1022         D = c->D += D;
1023     }
1024 }
1025 #endif
1026 
1027 #ifndef md5_block_data_order
1028 #ifdef X
1029 #undef X
1030 #endif
1031 void md5_block_data_order (MD5_CTX *c, const void *data_, int num)
1032 {
1033     const unsigned char *data=data_;
1034     register unsigned MD32_REG_T A,B,C,D,l;
1035 #ifndef MD32_XARRAY
1036     /* See comment in crypto/sha/sha_locl.h for details. */
1037     unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
1038                         XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
1039 # define X(i)   XX ## i
1040 #else
1041     mDNSu32 XX[MD5_LBLOCK];
1042 # define X(i)   XX[i]
1043 #endif
1044 
1045     A=c->A;
1046     B=c->B;
1047     C=c->C;
1048     D=c->D;
1049 
1050     for (; num--;)
1051     {
1052         HOST_c2l(data,l); X( 0)=l;      HOST_c2l(data,l); X( 1)=l;
1053         /* Round 0 */
1054         R0(A,B,C,D,X( 0), 7,0xd76aa478L);   HOST_c2l(data,l); X( 2)=l;
1055         R0(D,A,B,C,X( 1),12,0xe8c7b756L);   HOST_c2l(data,l); X( 3)=l;
1056         R0(C,D,A,B,X( 2),17,0x242070dbL);   HOST_c2l(data,l); X( 4)=l;
1057         R0(B,C,D,A,X( 3),22,0xc1bdceeeL);   HOST_c2l(data,l); X( 5)=l;
1058         R0(A,B,C,D,X( 4), 7,0xf57c0fafL);   HOST_c2l(data,l); X( 6)=l;
1059         R0(D,A,B,C,X( 5),12,0x4787c62aL);   HOST_c2l(data,l); X( 7)=l;
1060         R0(C,D,A,B,X( 6),17,0xa8304613L);   HOST_c2l(data,l); X( 8)=l;
1061         R0(B,C,D,A,X( 7),22,0xfd469501L);   HOST_c2l(data,l); X( 9)=l;
1062         R0(A,B,C,D,X( 8), 7,0x698098d8L);   HOST_c2l(data,l); X(10)=l;
1063         R0(D,A,B,C,X( 9),12,0x8b44f7afL);   HOST_c2l(data,l); X(11)=l;
1064         R0(C,D,A,B,X(10),17,0xffff5bb1L);   HOST_c2l(data,l); X(12)=l;
1065         R0(B,C,D,A,X(11),22,0x895cd7beL);   HOST_c2l(data,l); X(13)=l;
1066         R0(A,B,C,D,X(12), 7,0x6b901122L);   HOST_c2l(data,l); X(14)=l;
1067         R0(D,A,B,C,X(13),12,0xfd987193L);   HOST_c2l(data,l); X(15)=l;
1068         R0(C,D,A,B,X(14),17,0xa679438eL);
1069         R0(B,C,D,A,X(15),22,0x49b40821L);
1070         /* Round 1 */
1071         R1(A,B,C,D,X( 1), 5,0xf61e2562L);
1072         R1(D,A,B,C,X( 6), 9,0xc040b340L);
1073         R1(C,D,A,B,X(11),14,0x265e5a51L);
1074         R1(B,C,D,A,X( 0),20,0xe9b6c7aaL);
1075         R1(A,B,C,D,X( 5), 5,0xd62f105dL);
1076         R1(D,A,B,C,X(10), 9,0x02441453L);
1077         R1(C,D,A,B,X(15),14,0xd8a1e681L);
1078         R1(B,C,D,A,X( 4),20,0xe7d3fbc8L);
1079         R1(A,B,C,D,X( 9), 5,0x21e1cde6L);
1080         R1(D,A,B,C,X(14), 9,0xc33707d6L);
1081         R1(C,D,A,B,X( 3),14,0xf4d50d87L);
1082         R1(B,C,D,A,X( 8),20,0x455a14edL);
1083         R1(A,B,C,D,X(13), 5,0xa9e3e905L);
1084         R1(D,A,B,C,X( 2), 9,0xfcefa3f8L);
1085         R1(C,D,A,B,X( 7),14,0x676f02d9L);
1086         R1(B,C,D,A,X(12),20,0x8d2a4c8aL);
1087         /* Round 2 */
1088         R2(A,B,C,D,X( 5), 4,0xfffa3942L);
1089         R2(D,A,B,C,X( 8),11,0x8771f681L);
1090         R2(C,D,A,B,X(11),16,0x6d9d6122L);
1091         R2(B,C,D,A,X(14),23,0xfde5380cL);
1092         R2(A,B,C,D,X( 1), 4,0xa4beea44L);
1093         R2(D,A,B,C,X( 4),11,0x4bdecfa9L);
1094         R2(C,D,A,B,X( 7),16,0xf6bb4b60L);
1095         R2(B,C,D,A,X(10),23,0xbebfbc70L);
1096         R2(A,B,C,D,X(13), 4,0x289b7ec6L);
1097         R2(D,A,B,C,X( 0),11,0xeaa127faL);
1098         R2(C,D,A,B,X( 3),16,0xd4ef3085L);
1099         R2(B,C,D,A,X( 6),23,0x04881d05L);
1100         R2(A,B,C,D,X( 9), 4,0xd9d4d039L);
1101         R2(D,A,B,C,X(12),11,0xe6db99e5L);
1102         R2(C,D,A,B,X(15),16,0x1fa27cf8L);
1103         R2(B,C,D,A,X( 2),23,0xc4ac5665L);
1104         /* Round 3 */
1105         R3(A,B,C,D,X( 0), 6,0xf4292244L);
1106         R3(D,A,B,C,X( 7),10,0x432aff97L);
1107         R3(C,D,A,B,X(14),15,0xab9423a7L);
1108         R3(B,C,D,A,X( 5),21,0xfc93a039L);
1109         R3(A,B,C,D,X(12), 6,0x655b59c3L);
1110         R3(D,A,B,C,X( 3),10,0x8f0ccc92L);
1111         R3(C,D,A,B,X(10),15,0xffeff47dL);
1112         R3(B,C,D,A,X( 1),21,0x85845dd1L);
1113         R3(A,B,C,D,X( 8), 6,0x6fa87e4fL);
1114         R3(D,A,B,C,X(15),10,0xfe2ce6e0L);
1115         R3(C,D,A,B,X( 6),15,0xa3014314L);
1116         R3(B,C,D,A,X(13),21,0x4e0811a1L);
1117         R3(A,B,C,D,X( 4), 6,0xf7537e82L);
1118         R3(D,A,B,C,X(11),10,0xbd3af235L);
1119         R3(C,D,A,B,X( 2),15,0x2ad7d2bbL);
1120         R3(B,C,D,A,X( 9),21,0xeb86d391L);
1121 
1122         A = c->A += A;
1123         B = c->B += B;
1124         C = c->C += C;
1125         D = c->D += D;
1126     }
1127 }
1128 #endif
1129 
1130 
1131 // ***************************************************************************
1132 #if COMPILER_LIKES_PRAGMA_MARK
1133 #pragma mark - base64 -> binary conversion
1134 #endif
1135 
1136 static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1137 static const char Pad64 = '=';
1138 
1139 
1140 #define mDNSisspace(x) (x == '\t' || x == '\n' || x == '\v' || x == '\f' || x == '\r' || x == ' ')
1141 
1142 mDNSlocal const char *mDNSstrchr(const char *s, int c)
1143 {
1144     while (1)
1145     {
1146         if (c == *s) return s;
1147         if (!*s) return mDNSNULL;
1148         s++;
1149     }
1150 }
1151 
1152 // skips all whitespace anywhere.
1153 // converts characters, four at a time, starting at (or after)
1154 // src from base - 64 numbers into three 8 bit bytes in the target area.
1155 // it returns the number of data bytes stored at the target, or -1 on error.
1156 // adapted from BIND sources
1157 
1158 mDNSlocal mDNSs32 DNSDigest_Base64ToBin(const char *src, mDNSu8 *target, mDNSu32 targsize)
1159 {
1160     int tarindex, state, ch;
1161     const char *pos;
1162 
1163     state = 0;
1164     tarindex = 0;
1165 
1166     while ((ch = *src++) != '\0') {
1167         if (mDNSisspace(ch))    /* Skip whitespace anywhere. */
1168             continue;
1169 
1170         if (ch == Pad64)
1171             break;
1172 
1173         pos = mDNSstrchr(Base64, ch);
1174         if (pos == 0)       /* A non-base64 character. */
1175             return (-1);
1176 
1177         switch (state) {
1178         case 0:
1179             if (target) {
1180                 if ((mDNSu32)tarindex >= targsize)
1181                     return (-1);
1182                 target[tarindex] = (mDNSu8)((pos - Base64) << 2);
1183             }
1184             state = 1;
1185             break;
1186         case 1:
1187             if (target) {
1188                 if ((mDNSu32)tarindex + 1 >= targsize)
1189                     return (-1);
1190                 target[tarindex]   |=  (pos - Base64) >> 4;
1191                 target[tarindex+1]  = (mDNSu8)(((pos - Base64) & 0x0f) << 4);
1192             }
1193             tarindex++;
1194             state = 2;
1195             break;
1196         case 2:
1197             if (target) {
1198                 if ((mDNSu32)tarindex + 1 >= targsize)
1199                     return (-1);
1200                 target[tarindex]   |=  (pos - Base64) >> 2;
1201                 target[tarindex+1]  = (mDNSu8)(((pos - Base64) & 0x03) << 6);
1202             }
1203             tarindex++;
1204             state = 3;
1205             break;
1206         case 3:
1207             if (target) {
1208                 if ((mDNSu32)tarindex >= targsize)
1209                     return (-1);
1210                 target[tarindex] |= (pos - Base64);
1211             }
1212             tarindex++;
1213             state = 0;
1214             break;
1215         default:
1216             return -1;
1217         }
1218     }
1219 
1220     /*
1221      * We are done decoding Base-64 chars.  Let's see if we ended
1222      * on a byte boundary, and/or with erroneous trailing characters.
1223      */
1224 
1225     if (ch == Pad64) {      /* We got a pad char. */
1226         ch = *src++;        /* Skip it, get next. */
1227         switch (state) {
1228         case 0:     /* Invalid = in first position */
1229         case 1:     /* Invalid = in second position */
1230             return (-1);
1231 
1232         case 2:     /* Valid, means one byte of info */
1233             /* Skip any number of spaces. */
1234             for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1235                 if (!mDNSisspace(ch))
1236                     break;
1237             /* Make sure there is another trailing = sign. */
1238             if (ch != Pad64)
1239                 return (-1);
1240             ch = *src++;        /* Skip the = */
1241         /* Fall through to "single trailing =" case. */
1242         /* FALLTHROUGH */
1243 
1244         case 3:     /* Valid, means two bytes of info */
1245             /*
1246              * We know this char is an =.  Is there anything but
1247              * whitespace after it?
1248              */
1249             for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1250                 if (!mDNSisspace(ch))
1251                     return (-1);
1252 
1253             /*
1254              * Now make sure for cases 2 and 3 that the "extra"
1255              * bits that slopped past the last full byte were
1256              * zeros.  If we don't check them, they become a
1257              * subliminal channel.
1258              */
1259             if (target && target[tarindex] != 0)
1260                 return (-1);
1261         }
1262     } else {
1263         /*
1264          * We ended by seeing the end of the string.  Make sure we
1265          * have no partial bytes lying around.
1266          */
1267         if (state != 0)
1268             return (-1);
1269     }
1270 
1271     return (tarindex);
1272 }
1273 
1274 
1275 // ***************************************************************************
1276 #if COMPILER_LIKES_PRAGMA_MARK
1277 #pragma mark - API exported to mDNS Core
1278 #endif
1279 
1280 // Constants
1281 #define HMAC_IPAD   0x36
1282 #define HMAC_OPAD   0x5c
1283 #define MD5_LEN     16
1284 
1285 #define HMAC_MD5_AlgName (*(const domainname*) "\010" "hmac-md5" "\007" "sig-alg" "\003" "reg" "\003" "int")
1286 
1287 // Adapted from Appendix, RFC 2104
1288 mDNSlocal void DNSDigest_ConstructHMACKey(DomainAuthInfo *info, const mDNSu8 *key, mDNSu32 len)
1289 {
1290     MD5_CTX k;
1291     mDNSu8 buf[MD5_LEN];
1292     int i;
1293 
1294     // If key is longer than HMAC_LEN reset it to MD5(key)
1295     if (len > HMAC_LEN)
1296     {
1297         MD5_Init(&k);
1298         MD5_Update(&k, key, len);
1299         MD5_Final(buf, &k);
1300         key = buf;
1301         len = MD5_LEN;
1302     }
1303 
1304     // store key in pads
1305     mDNSPlatformMemZero(info->keydata_ipad, HMAC_LEN);
1306     mDNSPlatformMemZero(info->keydata_opad, HMAC_LEN);
1307     mDNSPlatformMemCopy(info->keydata_ipad, key, len);
1308     mDNSPlatformMemCopy(info->keydata_opad, key, len);
1309 
1310     // XOR key with ipad and opad values
1311     for (i = 0; i < HMAC_LEN; i++)
1312     {
1313         info->keydata_ipad[i] ^= HMAC_IPAD;
1314         info->keydata_opad[i] ^= HMAC_OPAD;
1315     }
1316 
1317 }
1318 
1319 mDNSexport mDNSs32 DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo *info, const char *b64key)
1320 {
1321     mDNSu8 keybuf[1024];
1322     mDNSs32 keylen = DNSDigest_Base64ToBin(b64key, keybuf, sizeof(keybuf));
1323     if (keylen < 0) return(keylen);
1324     DNSDigest_ConstructHMACKey(info, keybuf, (mDNSu32)keylen);
1325     return(keylen);
1326 }
1327 
1328 mDNSexport void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode)
1329 {
1330     AuthRecord tsig;
1331     mDNSu8  *rdata, *const countPtr = (mDNSu8 *)&msg->h.numAdditionals; // Get existing numAdditionals value
1332     mDNSu32 utc32;
1333     mDNSu8 utc48[6];
1334     mDNSu8 digest[MD5_LEN];
1335     mDNSu8 *ptr = *end;
1336     mDNSu32 len;
1337     mDNSOpaque16 buf;
1338     MD5_CTX c;
1339     mDNSu16 numAdditionals = (mDNSu16)((mDNSu16)countPtr[0] << 8 | countPtr[1]);
1340 
1341     // Init MD5 context, digest inner key pad and message
1342     MD5_Init(&c);
1343     MD5_Update(&c, info->keydata_ipad, HMAC_LEN);
1344     MD5_Update(&c, (mDNSu8 *)msg, (unsigned long)(*end - (mDNSu8 *)msg));
1345 
1346     // Construct TSIG RR, digesting variables as apporpriate
1347     mDNS_SetupResourceRecord(&tsig, mDNSNULL, 0, kDNSType_TSIG, 0, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
1348 
1349     // key name
1350     AssignDomainName(&tsig.namestorage, &info->keyname);
1351     MD5_Update(&c, info->keyname.c, DomainNameLength(&info->keyname));
1352 
1353     // class
1354     tsig.resrec.rrclass = kDNSQClass_ANY;
1355     buf = mDNSOpaque16fromIntVal(kDNSQClass_ANY);
1356     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1357 
1358     // ttl
1359     tsig.resrec.rroriginalttl = 0;
1360     MD5_Update(&c, (mDNSu8 *)&tsig.resrec.rroriginalttl, sizeof(tsig.resrec.rroriginalttl));
1361 
1362     // alg name
1363     AssignDomainName(&tsig.resrec.rdata->u.name, &HMAC_MD5_AlgName);
1364     len = DomainNameLength(&HMAC_MD5_AlgName);
1365     rdata = tsig.resrec.rdata->u.data + len;
1366     MD5_Update(&c, HMAC_MD5_AlgName.c, len);
1367 
1368     // time
1369     // get UTC (universal time), convert to 48-bit unsigned in network byte order
1370     utc32 = (mDNSu32)mDNSPlatformUTC();
1371     if (utc32 == (unsigned)-1) { LogMsg("ERROR: DNSDigest_SignMessage - mDNSPlatformUTC returned bad time -1"); *end = mDNSNULL; }
1372     utc48[0] = 0;
1373     utc48[1] = 0;
1374     utc48[2] = (mDNSu8)((utc32 >> 24) & 0xff);
1375     utc48[3] = (mDNSu8)((utc32 >> 16) & 0xff);
1376     utc48[4] = (mDNSu8)((utc32 >>  8) & 0xff);
1377     utc48[5] = (mDNSu8)( utc32        & 0xff);
1378 
1379     mDNSPlatformMemCopy(rdata, utc48, 6);
1380     rdata += 6;
1381     MD5_Update(&c, utc48, 6);
1382 
1383     // 300 sec is fudge recommended in RFC 2485
1384     rdata[0] = (mDNSu8)((300 >> 8)  & 0xff);
1385     rdata[1] = (mDNSu8)( 300        & 0xff);
1386     MD5_Update(&c, rdata, sizeof(mDNSOpaque16));
1387     rdata += sizeof(mDNSOpaque16);
1388 
1389     // digest error (tcode) and other data len (zero) - we'll add them to the rdata later
1390     buf.b[0] = (mDNSu8)((tcode >> 8) & 0xff);
1391     buf.b[1] = (mDNSu8)( tcode       & 0xff);
1392     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // error
1393     buf.NotAnInteger = 0;
1394     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // other data len
1395 
1396     // finish the message & tsig var hash
1397     MD5_Final(digest, &c);
1398 
1399     // perform outer MD5 (outer key pad, inner digest)
1400     MD5_Init(&c);
1401     MD5_Update(&c, info->keydata_opad, HMAC_LEN);
1402     MD5_Update(&c, digest, MD5_LEN);
1403     MD5_Final(digest, &c);
1404 
1405     // set remaining rdata fields
1406     rdata[0] = (mDNSu8)((MD5_LEN >> 8)  & 0xff);
1407     rdata[1] = (mDNSu8)( MD5_LEN        & 0xff);
1408     rdata += sizeof(mDNSOpaque16);
1409     mDNSPlatformMemCopy(rdata, digest, MD5_LEN);                          // MAC
1410     rdata += MD5_LEN;
1411     rdata[0] = msg->h.id.b[0];                                            // original ID
1412     rdata[1] = msg->h.id.b[1];
1413     rdata[2] = (mDNSu8)((tcode >> 8) & 0xff);
1414     rdata[3] = (mDNSu8)( tcode       & 0xff);
1415     rdata[4] = 0;                                                         // other data len
1416     rdata[5] = 0;
1417     rdata += 6;
1418 
1419     tsig.resrec.rdlength = (mDNSu16)(rdata - tsig.resrec.rdata->u.data);
1420     *end = PutResourceRecordTTLJumbo(msg, ptr, &numAdditionals, &tsig.resrec, 0);
1421     if (!*end) { LogMsg("ERROR: DNSDigest_SignMessage - could not put TSIG"); *end = mDNSNULL; return; }
1422 
1423     // Write back updated numAdditionals value
1424     countPtr[0] = (mDNSu8)(numAdditionals >> 8);
1425     countPtr[1] = (mDNSu8)(numAdditionals &  0xFF);
1426 }
1427 
1428 mDNSexport mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord * lcr, DomainAuthInfo *info, mDNSu16 * rcode, mDNSu16 * tcode)
1429 {
1430     mDNSu8          *   ptr = (mDNSu8*) &lcr->r.resrec.rdata->u.data;
1431     mDNSs32 now;
1432     mDNSs32 then;
1433     mDNSu8 thisDigest[MD5_LEN];
1434     mDNSu8 thatDigest[MD5_LEN];
1435     mDNSOpaque16 buf;
1436     mDNSu8 utc48[6];
1437     mDNSs32 delta;
1438     mDNSu16 fudge;
1439     domainname      *   algo;
1440     MD5_CTX c;
1441     mDNSBool ok = mDNSfalse;
1442 
1443     // We only support HMAC-MD5 for now
1444 
1445     algo = (domainname*) ptr;
1446 
1447     if (!SameDomainName(algo, &HMAC_MD5_AlgName))
1448     {
1449         LogMsg("ERROR: DNSDigest_VerifyMessage - TSIG algorithm not supported: %##s", algo->c);
1450         *rcode = kDNSFlag1_RC_NotAuth;
1451         *tcode = TSIG_ErrBadKey;
1452         ok = mDNSfalse;
1453         goto exit;
1454     }
1455 
1456     ptr += DomainNameLength(algo);
1457 
1458     // Check the times
1459 
1460     now = mDNSPlatformUTC();
1461     if (now == -1)
1462     {
1463         LogMsg("ERROR: DNSDigest_VerifyMessage - mDNSPlatformUTC returned bad time -1");
1464         *rcode = kDNSFlag1_RC_NotAuth;
1465         *tcode = TSIG_ErrBadTime;
1466         ok = mDNSfalse;
1467         goto exit;
1468     }
1469 
1470     // Get the 48 bit time field, skipping over the first word
1471 
1472     utc48[0] = *ptr++;
1473     utc48[1] = *ptr++;
1474     utc48[2] = *ptr++;
1475     utc48[3] = *ptr++;
1476     utc48[4] = *ptr++;
1477     utc48[5] = *ptr++;
1478 
1479     then  = (mDNSs32)NToH32(utc48 + sizeof(mDNSu16));
1480 
1481     fudge = NToH16(ptr);
1482 
1483     ptr += sizeof(mDNSu16);
1484 
1485     delta = (now > then) ? now - then : then - now;
1486 
1487     if (delta > fudge)
1488     {
1489         LogMsg("ERROR: DNSDigest_VerifyMessage - time skew > %d", fudge);
1490         *rcode = kDNSFlag1_RC_NotAuth;
1491         *tcode = TSIG_ErrBadTime;
1492         ok = mDNSfalse;
1493         goto exit;
1494     }
1495 
1496     // MAC size
1497 
1498     ptr += sizeof(mDNSu16);
1499 
1500     // MAC
1501 
1502     mDNSPlatformMemCopy(thatDigest, ptr, MD5_LEN);
1503 
1504     // Init MD5 context, digest inner key pad and message
1505 
1506     MD5_Init(&c);
1507     MD5_Update(&c, info->keydata_ipad, HMAC_LEN);
1508     MD5_Update(&c, (mDNSu8*) msg, (unsigned long)(end - (mDNSu8*) msg));
1509 
1510     // Key name
1511 
1512     MD5_Update(&c, lcr->r.resrec.name->c, DomainNameLength(lcr->r.resrec.name));
1513 
1514     // Class name
1515 
1516     buf = mDNSOpaque16fromIntVal(lcr->r.resrec.rrclass);
1517     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1518 
1519     // TTL
1520 
1521     MD5_Update(&c, (mDNSu8*) &lcr->r.resrec.rroriginalttl, sizeof(lcr->r.resrec.rroriginalttl));
1522 
1523     // Algorithm
1524 
1525     MD5_Update(&c, algo->c, DomainNameLength(algo));
1526 
1527     // Time
1528 
1529     MD5_Update(&c, utc48, 6);
1530 
1531     // Fudge
1532 
1533     buf = mDNSOpaque16fromIntVal(fudge);
1534     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1535 
1536     // Digest error and other data len (both zero) - we'll add them to the rdata later
1537 
1538     buf.NotAnInteger = 0;
1539     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // error
1540     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // other data len
1541 
1542     // Finish the message & tsig var hash
1543 
1544     MD5_Final(thisDigest, &c);
1545 
1546     // perform outer MD5 (outer key pad, inner digest)
1547 
1548     MD5_Init(&c);
1549     MD5_Update(&c, info->keydata_opad, HMAC_LEN);
1550     MD5_Update(&c, thisDigest, MD5_LEN);
1551     MD5_Final(thisDigest, &c);
1552 
1553     if (!mDNSPlatformMemSame(thisDigest, thatDigest, MD5_LEN))
1554     {
1555         LogMsg("ERROR: DNSDigest_VerifyMessage - bad signature");
1556         *rcode = kDNSFlag1_RC_NotAuth;
1557         *tcode = TSIG_ErrBadSig;
1558         ok = mDNSfalse;
1559         goto exit;
1560     }
1561 
1562     // set remaining rdata fields
1563     ok = mDNStrue;
1564 
1565 exit:
1566 
1567     return ok;
1568 }
1569 
1570 
1571 #ifdef __cplusplus
1572 }
1573 #endif
1574