xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/DNSDigest.c (revision 3dfe801733ea71102fa4b1f79dddf16ee3ea546f)
1 /*
2  * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
3  * Copyright (c) 2016 by Delphix. 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             /* FALLTHROUGH */                       \
577         case 1: l|=((unsigned long)(*((c)++)))<<16; \
578             /* FALLTHROUGH */                       \
579         case 2: l|=((unsigned long)(*((c)++)))<< 8; \
580             /* FALLTHROUGH */                       \
581         case 3: l|=((unsigned long)(*((c)++)));     \
582         } }
583 #define HOST_p_c2l_p(c,l,sc,len) {                  \
584         switch (sc) {                               \
585         case 0: l =((unsigned long)(*((c)++)))<<24; \
586             if (--len == 0) break;                  \
587             /* FALLTHROUGH */                       \
588         case 1: l|=((unsigned long)(*((c)++)))<<16; \
589             if (--len == 0) break;                  \
590             /* FALLTHROUGH */                       \
591         case 2: l|=((unsigned long)(*((c)++)))<< 8; \
592         } }
593 /* NOTE the pointer is not incremented at the end of this */
594 #define HOST_c2l_p(c,l,n)   {                       \
595         l=0; (c)+=n;                                \
596         switch (n) {                                \
597         case 3: l =((unsigned long)(*(--(c))))<< 8; \
598             /* FALLTHROUGH */                       \
599         case 2: l|=((unsigned long)(*(--(c))))<<16; \
600             /* FALLTHROUGH */                       \
601         case 1: l|=((unsigned long)(*(--(c))))<<24; \
602         } }
603 #define _HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)>>24)&0xff),  \
604                          *((c)++)=(unsigned char)(((l)>>16)&0xff),  \
605                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),  \
606                          *((c)++)=(unsigned char)(((l)    )&0xff),  \
607                          l)
608 
609 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
610 
611 #define _HOST_c2l(c,l)  (l =(((unsigned long)(*((c)++)))    ),      \
612                          l|=(((unsigned long)(*((c)++)))<< 8),      \
613                          l|=(((unsigned long)(*((c)++)))<<16),      \
614                          l|=(((unsigned long)(*((c)++)))<<24),      \
615                          l)
616 #define HOST_p_c2l(c,l,n)   {                       \
617         switch (n) {                                \
618         case 0: l =((unsigned long)(*((c)++)));     \
619             /* FALLTHROUGH */                       \
620         case 1: l|=((unsigned long)(*((c)++)))<< 8; \
621             /* FALLTHROUGH */                       \
622         case 2: l|=((unsigned long)(*((c)++)))<<16; \
623             /* FALLTHROUGH */                       \
624         case 3: l|=((unsigned long)(*((c)++)))<<24; \
625         } }
626 #define HOST_p_c2l_p(c,l,sc,len) {                  \
627         switch (sc) {                               \
628         case 0: l =((unsigned long)(*((c)++)));     \
629             if (--len == 0) break;                  \
630             /* FALLTHROUGH */                       \
631         case 1: l|=((unsigned long)(*((c)++)))<< 8; \
632             if (--len == 0) break;                  \
633             /* FALLTHROUGH */                       \
634         case 2: l|=((unsigned long)(*((c)++)))<<16; \
635         } }
636 /* NOTE the pointer is not incremented at the end of this */
637 #define HOST_c2l_p(c,l,n)   {                       \
638         l=0; (c)+=n;                                \
639         switch (n) {                                \
640         case 3: l =((unsigned long)(*(--(c))))<<16; \
641             /* FALLTHROUGH */                       \
642         case 2: l|=((unsigned long)(*(--(c))))<< 8; \
643             /* FALLTHROUGH */                       \
644         case 1: l|=((unsigned long)(*(--(c))));     \
645         } }
646 #define _HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)    )&0xff),  \
647                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),  \
648                          *((c)++)=(unsigned char)(((l)>>16)&0xff),  \
649                          *((c)++)=(unsigned char)(((l)>>24)&0xff),  \
650                          l)
651 
652 #endif
653 
654 /*
655  * Time for some action:-)
656  */
657 
658 int HASH_UPDATE (HASH_CTX *c, const void *data_, unsigned long len)
659 {
660     const unsigned char *data=(const unsigned char *)data_;
661     const unsigned char * const data_end=(const unsigned char *)data_;
662     register HASH_LONG * p;
663     register unsigned long l;
664     int sw,sc,ew,ec;
665 
666     if (len==0) return 1;
667 
668     l=(c->Nl+(len<<3))&0xffffffffL;
669     /* 95-05-24 eay Fixed a bug with the overflow handling, thanks to
670      * Wei Dai <weidai@eskimo.com> for pointing it out. */
671     if (l < c->Nl) /* overflow */
672         c->Nh++;
673     c->Nh+=(len>>29);
674     c->Nl=l;
675 
676     if (c->num != 0)
677     {
678         p=c->data;
679         sw=c->num>>2;
680         sc=c->num&0x03;
681 
682         if ((c->num+len) >= HASH_CBLOCK)
683         {
684             l=p[sw]; HOST_p_c2l(data,l,sc); p[sw++]=l;
685             for (; (sw < HASH_LBLOCK) && ((data_end - data) >= 4); sw++)
686             {
687                 HOST_c2l(data,l); p[sw]=l;
688             }
689             HASH_BLOCK_HOST_ORDER (c,p,1);
690             len-=(HASH_CBLOCK-c->num);
691             c->num=0;
692             /* drop through and do the rest */
693         }
694         else
695         {
696             c->num+=len;
697             if ((sc+len) < 4) /* ugly, add char's to a word */
698             {
699                 l=p[sw]; HOST_p_c2l_p(data,l,sc,len); p[sw]=l;
700             }
701             else
702             {
703                 ew=(c->num>>2);
704                 ec=(c->num&0x03);
705                 if (sc)
706                     l=p[sw];
707                 HOST_p_c2l(data,l,sc);
708                 p[sw++]=l;
709                 for (; (sw < ew) && ((data_end - data) >= 4); sw++)
710                 {
711                     HOST_c2l(data,l); p[sw]=l;
712                 }
713                 if (ec)
714                 {
715                     HOST_c2l_p(data,l,ec); p[sw]=l;
716                 }
717             }
718             return 1;
719         }
720     }
721 
722     sw=(int)(len/HASH_CBLOCK);
723     if (sw > 0)
724     {
725 #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
726         /*
727          * Note that HASH_BLOCK_DATA_ORDER_ALIGNED gets defined
728          * only if sizeof(HASH_LONG)==4.
729          */
730         if ((((unsigned long)data)%4) == 0)
731         {
732             /* data is properly aligned so that we can cast it: */
733             HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,sw);
734             sw*=HASH_CBLOCK;
735             data+=sw;
736             len-=sw;
737         }
738         else
739 #if !defined(HASH_BLOCK_DATA_ORDER)
740             while (sw--)
741             {
742                 mDNSPlatformMemCopy(p=c->data,data,HASH_CBLOCK);
743                 HASH_BLOCK_DATA_ORDER_ALIGNED(c,p,1);
744                 data+=HASH_CBLOCK;
745                 len-=HASH_CBLOCK;
746             }
747 #endif
748 #endif
749 #if defined(HASH_BLOCK_DATA_ORDER)
750         {
751             HASH_BLOCK_DATA_ORDER(c,data,sw);
752             sw*=HASH_CBLOCK;
753             data+=sw;
754             len-=sw;
755         }
756 #endif
757     }
758 
759     if (len!=0)
760     {
761         p = c->data;
762         c->num = (int)len;
763         ew=(int)(len>>2);   /* words to copy */
764         ec=(int)(len&0x03);
765         for (; ew && ((data_end - data) >= 4); ew--,p++)
766         {
767             HOST_c2l(data,l); *p=l;
768         }
769         HOST_c2l_p(data,l,ec);
770         *p=l;
771     }
772     return 1;
773 }
774 
775 
776 void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data)
777 {
778 #if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
779     if ((((unsigned long)data)%4) == 0)
780         /* data is properly aligned so that we can cast it: */
781         HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,1);
782     else
783 #if !defined(HASH_BLOCK_DATA_ORDER)
784     {
785         mDNSPlatformMemCopy(c->data,data,HASH_CBLOCK);
786         HASH_BLOCK_DATA_ORDER_ALIGNED (c,c->data,1);
787     }
788 #endif
789 #endif
790 #if defined(HASH_BLOCK_DATA_ORDER)
791     HASH_BLOCK_DATA_ORDER (c,data,1);
792 #endif
793 }
794 
795 
796 int HASH_FINAL (unsigned char *md, HASH_CTX *c)
797 {
798     register HASH_LONG *p;
799     register unsigned long l;
800     register int i,j;
801     static const unsigned char end[4]={0x80,0x00,0x00,0x00};
802     const unsigned char *cp=end;
803 
804     /* c->num should definitly have room for at least one more byte. */
805     p=c->data;
806     i=c->num>>2;
807     j=c->num&0x03;
808 
809 #if 0
810     /* purify often complains about the following line as an
811      * Uninitialized Memory Read.  While this can be true, the
812      * following p_c2l macro will reset l when that case is true.
813      * This is because j&0x03 contains the number of 'valid' bytes
814      * already in p[i].  If and only if j&0x03 == 0, the UMR will
815      * occur but this is also the only time p_c2l will do
816      * l= *(cp++) instead of l|= *(cp++)
817      * Many thanks to Alex Tang <altitude@cic.net> for pickup this
818      * 'potential bug' */
819 #ifdef PURIFY
820     if (j==0) p[i]=0; /* Yeah, but that's not the way to fix it:-) */
821 #endif
822     l=p[i];
823 #else
824     l = (j==0) ? 0 : p[i];
825 #endif
826     HOST_p_c2l(cp,l,j); p[i++]=l; /* i is the next 'undefined word' */
827 
828     if (i>(HASH_LBLOCK-2)) /* save room for Nl and Nh */
829     {
830         if (i<HASH_LBLOCK) p[i]=0;
831         HASH_BLOCK_HOST_ORDER (c,p,1);
832         i=0;
833     }
834     for (; i<(HASH_LBLOCK-2); i++)
835         p[i]=0;
836 
837 #if   defined(DATA_ORDER_IS_BIG_ENDIAN)
838     p[HASH_LBLOCK-2]=c->Nh;
839     p[HASH_LBLOCK-1]=c->Nl;
840 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
841     p[HASH_LBLOCK-2]=c->Nl;
842     p[HASH_LBLOCK-1]=c->Nh;
843 #endif
844     HASH_BLOCK_HOST_ORDER (c,p,1);
845 
846 #ifndef HASH_MAKE_STRING
847 #error "HASH_MAKE_STRING must be defined!"
848 #else
849     HASH_MAKE_STRING(c,md);
850 #endif
851 
852     c->num=0;
853     /* clear stuff, HASH_BLOCK may be leaving some stuff on the stack
854      * but I'm not worried :-)
855        OPENSSL_cleanse((void *)c,sizeof(HASH_CTX));
856      */
857     return 1;
858 }
859 
860 #ifndef MD32_REG_T
861 #define MD32_REG_T long
862 /*
863  * This comment was originaly written for MD5, which is why it
864  * discusses A-D. But it basically applies to all 32-bit digests,
865  * which is why it was moved to common header file.
866  *
867  * In case you wonder why A-D are declared as long and not
868  * as mDNSu32. Doing so results in slight performance
869  * boost on LP64 architectures. The catch is we don't
870  * really care if 32 MSBs of a 64-bit register get polluted
871  * with eventual overflows as we *save* only 32 LSBs in
872  * *either* case. Now declaring 'em long excuses the compiler
873  * from keeping 32 MSBs zeroed resulting in 13% performance
874  * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
875  * Well, to be honest it should say that this *prevents*
876  * performance degradation.
877  *				<appro@fy.chalmers.se>
878  * Apparently there're LP64 compilers that generate better
879  * code if A-D are declared int. Most notably GCC-x86_64
880  * generates better code.
881  *				<appro@fy.chalmers.se>
882  */
883 #endif
884 
885 
886 // from md5_locl.h (continued)
887 
888 /*
889  #define	F(x,y,z)	(((x) & (y))  |  ((~(x)) & (z)))
890  #define	G(x,y,z)	(((x) & (z))  |  ((y) & (~(z))))
891  */
892 
893 /* As pointed out by Wei Dai <weidai@eskimo.com>, the above can be
894  * simplified to the code below.  Wei attributes these optimizations
895  * to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
896  */
897 #define F(b,c,d)    ((((c) ^ (d)) & (b)) ^ (d))
898 #define G(b,c,d)    ((((b) ^ (c)) & (d)) ^ (c))
899 #define H(b,c,d)    ((b) ^ (c) ^ (d))
900 #define I(b,c,d)    (((~(d)) | (b)) ^ (c))
901 
902 #define R0(a,b,c,d,k,s,t) { \
903         a+=((k)+(t)+F((b),(c),(d))); \
904         a=ROTATE(a,s); \
905         a+=b; }; \
906 
907 #define R1(a,b,c,d,k,s,t) { \
908         a+=((k)+(t)+G((b),(c),(d))); \
909         a=ROTATE(a,s); \
910         a+=b; };
911 
912 #define R2(a,b,c,d,k,s,t) { \
913         a+=((k)+(t)+H((b),(c),(d))); \
914         a=ROTATE(a,s); \
915         a+=b; };
916 
917 #define R3(a,b,c,d,k,s,t) { \
918         a+=((k)+(t)+I((b),(c),(d))); \
919         a=ROTATE(a,s); \
920         a+=b; };
921 
922 // from md5_dgst.c
923 
924 
925 /* Implemented from RFC1321 The MD5 Message-Digest Algorithm
926  */
927 
928 #define INIT_DATA_A (unsigned long)0x67452301L
929 #define INIT_DATA_B (unsigned long)0xefcdab89L
930 #define INIT_DATA_C (unsigned long)0x98badcfeL
931 #define INIT_DATA_D (unsigned long)0x10325476L
932 
933 int MD5_Init(MD5_CTX *c)
934 {
935     c->A=INIT_DATA_A;
936     c->B=INIT_DATA_B;
937     c->C=INIT_DATA_C;
938     c->D=INIT_DATA_D;
939     c->Nl=0;
940     c->Nh=0;
941     c->num=0;
942     return 1;
943 }
944 
945 #ifndef md5_block_host_order
946 void md5_block_host_order (MD5_CTX *c, const void *data, int num)
947 {
948     const mDNSu32 *X=(const mDNSu32 *)data;
949     register unsigned MD32_REG_T A,B,C,D;
950 
951     A=c->A;
952     B=c->B;
953     C=c->C;
954     D=c->D;
955 
956     for (; num--; X+=HASH_LBLOCK)
957     {
958         /* Round 0 */
959         R0(A,B,C,D,X[ 0], 7,0xd76aa478L);
960         R0(D,A,B,C,X[ 1],12,0xe8c7b756L);
961         R0(C,D,A,B,X[ 2],17,0x242070dbL);
962         R0(B,C,D,A,X[ 3],22,0xc1bdceeeL);
963         R0(A,B,C,D,X[ 4], 7,0xf57c0fafL);
964         R0(D,A,B,C,X[ 5],12,0x4787c62aL);
965         R0(C,D,A,B,X[ 6],17,0xa8304613L);
966         R0(B,C,D,A,X[ 7],22,0xfd469501L);
967         R0(A,B,C,D,X[ 8], 7,0x698098d8L);
968         R0(D,A,B,C,X[ 9],12,0x8b44f7afL);
969         R0(C,D,A,B,X[10],17,0xffff5bb1L);
970         R0(B,C,D,A,X[11],22,0x895cd7beL);
971         R0(A,B,C,D,X[12], 7,0x6b901122L);
972         R0(D,A,B,C,X[13],12,0xfd987193L);
973         R0(C,D,A,B,X[14],17,0xa679438eL);
974         R0(B,C,D,A,X[15],22,0x49b40821L);
975         /* Round 1 */
976         R1(A,B,C,D,X[ 1], 5,0xf61e2562L);
977         R1(D,A,B,C,X[ 6], 9,0xc040b340L);
978         R1(C,D,A,B,X[11],14,0x265e5a51L);
979         R1(B,C,D,A,X[ 0],20,0xe9b6c7aaL);
980         R1(A,B,C,D,X[ 5], 5,0xd62f105dL);
981         R1(D,A,B,C,X[10], 9,0x02441453L);
982         R1(C,D,A,B,X[15],14,0xd8a1e681L);
983         R1(B,C,D,A,X[ 4],20,0xe7d3fbc8L);
984         R1(A,B,C,D,X[ 9], 5,0x21e1cde6L);
985         R1(D,A,B,C,X[14], 9,0xc33707d6L);
986         R1(C,D,A,B,X[ 3],14,0xf4d50d87L);
987         R1(B,C,D,A,X[ 8],20,0x455a14edL);
988         R1(A,B,C,D,X[13], 5,0xa9e3e905L);
989         R1(D,A,B,C,X[ 2], 9,0xfcefa3f8L);
990         R1(C,D,A,B,X[ 7],14,0x676f02d9L);
991         R1(B,C,D,A,X[12],20,0x8d2a4c8aL);
992         /* Round 2 */
993         R2(A,B,C,D,X[ 5], 4,0xfffa3942L);
994         R2(D,A,B,C,X[ 8],11,0x8771f681L);
995         R2(C,D,A,B,X[11],16,0x6d9d6122L);
996         R2(B,C,D,A,X[14],23,0xfde5380cL);
997         R2(A,B,C,D,X[ 1], 4,0xa4beea44L);
998         R2(D,A,B,C,X[ 4],11,0x4bdecfa9L);
999         R2(C,D,A,B,X[ 7],16,0xf6bb4b60L);
1000         R2(B,C,D,A,X[10],23,0xbebfbc70L);
1001         R2(A,B,C,D,X[13], 4,0x289b7ec6L);
1002         R2(D,A,B,C,X[ 0],11,0xeaa127faL);
1003         R2(C,D,A,B,X[ 3],16,0xd4ef3085L);
1004         R2(B,C,D,A,X[ 6],23,0x04881d05L);
1005         R2(A,B,C,D,X[ 9], 4,0xd9d4d039L);
1006         R2(D,A,B,C,X[12],11,0xe6db99e5L);
1007         R2(C,D,A,B,X[15],16,0x1fa27cf8L);
1008         R2(B,C,D,A,X[ 2],23,0xc4ac5665L);
1009         /* Round 3 */
1010         R3(A,B,C,D,X[ 0], 6,0xf4292244L);
1011         R3(D,A,B,C,X[ 7],10,0x432aff97L);
1012         R3(C,D,A,B,X[14],15,0xab9423a7L);
1013         R3(B,C,D,A,X[ 5],21,0xfc93a039L);
1014         R3(A,B,C,D,X[12], 6,0x655b59c3L);
1015         R3(D,A,B,C,X[ 3],10,0x8f0ccc92L);
1016         R3(C,D,A,B,X[10],15,0xffeff47dL);
1017         R3(B,C,D,A,X[ 1],21,0x85845dd1L);
1018         R3(A,B,C,D,X[ 8], 6,0x6fa87e4fL);
1019         R3(D,A,B,C,X[15],10,0xfe2ce6e0L);
1020         R3(C,D,A,B,X[ 6],15,0xa3014314L);
1021         R3(B,C,D,A,X[13],21,0x4e0811a1L);
1022         R3(A,B,C,D,X[ 4], 6,0xf7537e82L);
1023         R3(D,A,B,C,X[11],10,0xbd3af235L);
1024         R3(C,D,A,B,X[ 2],15,0x2ad7d2bbL);
1025         R3(B,C,D,A,X[ 9],21,0xeb86d391L);
1026 
1027         A = c->A += A;
1028         B = c->B += B;
1029         C = c->C += C;
1030         D = c->D += D;
1031     }
1032 }
1033 #endif
1034 
1035 #ifndef md5_block_data_order
1036 #ifdef X
1037 #undef X
1038 #endif
1039 void md5_block_data_order (MD5_CTX *c, const void *data_, int num)
1040 {
1041     const unsigned char *data=data_;
1042     register unsigned MD32_REG_T A,B,C,D,l;
1043 #ifndef MD32_XARRAY
1044     /* See comment in crypto/sha/sha_locl.h for details. */
1045     unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
1046                         XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
1047 # define X(i)   XX ## i
1048 #else
1049     mDNSu32 XX[MD5_LBLOCK];
1050 # define X(i)   XX[i]
1051 #endif
1052 
1053     A=c->A;
1054     B=c->B;
1055     C=c->C;
1056     D=c->D;
1057 
1058 #if defined(__clang_analyzer__)
1059     // Get rid of false positive analyzer warning.
1060     for (const unsigned char *_ptr = data; _ptr < &data[num * HASH_CBLOCK]; ++_ptr) {}
1061 #endif
1062     for (; num--;)
1063     {
1064         HOST_c2l(data,l); X( 0)=l;      HOST_c2l(data,l); X( 1)=l;
1065         /* Round 0 */
1066         R0(A,B,C,D,X( 0), 7,0xd76aa478L);   HOST_c2l(data,l); X( 2)=l;
1067         R0(D,A,B,C,X( 1),12,0xe8c7b756L);   HOST_c2l(data,l); X( 3)=l;
1068         R0(C,D,A,B,X( 2),17,0x242070dbL);   HOST_c2l(data,l); X( 4)=l;
1069         R0(B,C,D,A,X( 3),22,0xc1bdceeeL);   HOST_c2l(data,l); X( 5)=l;
1070         R0(A,B,C,D,X( 4), 7,0xf57c0fafL);   HOST_c2l(data,l); X( 6)=l;
1071         R0(D,A,B,C,X( 5),12,0x4787c62aL);   HOST_c2l(data,l); X( 7)=l;
1072         R0(C,D,A,B,X( 6),17,0xa8304613L);   HOST_c2l(data,l); X( 8)=l;
1073         R0(B,C,D,A,X( 7),22,0xfd469501L);   HOST_c2l(data,l); X( 9)=l;
1074         R0(A,B,C,D,X( 8), 7,0x698098d8L);   HOST_c2l(data,l); X(10)=l;
1075         R0(D,A,B,C,X( 9),12,0x8b44f7afL);   HOST_c2l(data,l); X(11)=l;
1076         R0(C,D,A,B,X(10),17,0xffff5bb1L);   HOST_c2l(data,l); X(12)=l;
1077         R0(B,C,D,A,X(11),22,0x895cd7beL);   HOST_c2l(data,l); X(13)=l;
1078         R0(A,B,C,D,X(12), 7,0x6b901122L);   HOST_c2l(data,l); X(14)=l;
1079         R0(D,A,B,C,X(13),12,0xfd987193L);   HOST_c2l(data,l); X(15)=l;
1080         R0(C,D,A,B,X(14),17,0xa679438eL);
1081         R0(B,C,D,A,X(15),22,0x49b40821L);
1082         /* Round 1 */
1083         R1(A,B,C,D,X( 1), 5,0xf61e2562L);
1084         R1(D,A,B,C,X( 6), 9,0xc040b340L);
1085         R1(C,D,A,B,X(11),14,0x265e5a51L);
1086         R1(B,C,D,A,X( 0),20,0xe9b6c7aaL);
1087         R1(A,B,C,D,X( 5), 5,0xd62f105dL);
1088         R1(D,A,B,C,X(10), 9,0x02441453L);
1089         R1(C,D,A,B,X(15),14,0xd8a1e681L);
1090         R1(B,C,D,A,X( 4),20,0xe7d3fbc8L);
1091         R1(A,B,C,D,X( 9), 5,0x21e1cde6L);
1092         R1(D,A,B,C,X(14), 9,0xc33707d6L);
1093         R1(C,D,A,B,X( 3),14,0xf4d50d87L);
1094         R1(B,C,D,A,X( 8),20,0x455a14edL);
1095         R1(A,B,C,D,X(13), 5,0xa9e3e905L);
1096         R1(D,A,B,C,X( 2), 9,0xfcefa3f8L);
1097         R1(C,D,A,B,X( 7),14,0x676f02d9L);
1098         R1(B,C,D,A,X(12),20,0x8d2a4c8aL);
1099         /* Round 2 */
1100         R2(A,B,C,D,X( 5), 4,0xfffa3942L);
1101         R2(D,A,B,C,X( 8),11,0x8771f681L);
1102         R2(C,D,A,B,X(11),16,0x6d9d6122L);
1103         R2(B,C,D,A,X(14),23,0xfde5380cL);
1104         R2(A,B,C,D,X( 1), 4,0xa4beea44L);
1105         R2(D,A,B,C,X( 4),11,0x4bdecfa9L);
1106         R2(C,D,A,B,X( 7),16,0xf6bb4b60L);
1107         R2(B,C,D,A,X(10),23,0xbebfbc70L);
1108         R2(A,B,C,D,X(13), 4,0x289b7ec6L);
1109         R2(D,A,B,C,X( 0),11,0xeaa127faL);
1110         R2(C,D,A,B,X( 3),16,0xd4ef3085L);
1111         R2(B,C,D,A,X( 6),23,0x04881d05L);
1112         R2(A,B,C,D,X( 9), 4,0xd9d4d039L);
1113         R2(D,A,B,C,X(12),11,0xe6db99e5L);
1114         R2(C,D,A,B,X(15),16,0x1fa27cf8L);
1115         R2(B,C,D,A,X( 2),23,0xc4ac5665L);
1116         /* Round 3 */
1117         R3(A,B,C,D,X( 0), 6,0xf4292244L);
1118         R3(D,A,B,C,X( 7),10,0x432aff97L);
1119         R3(C,D,A,B,X(14),15,0xab9423a7L);
1120         R3(B,C,D,A,X( 5),21,0xfc93a039L);
1121         R3(A,B,C,D,X(12), 6,0x655b59c3L);
1122         R3(D,A,B,C,X( 3),10,0x8f0ccc92L);
1123         R3(C,D,A,B,X(10),15,0xffeff47dL);
1124         R3(B,C,D,A,X( 1),21,0x85845dd1L);
1125         R3(A,B,C,D,X( 8), 6,0x6fa87e4fL);
1126         R3(D,A,B,C,X(15),10,0xfe2ce6e0L);
1127         R3(C,D,A,B,X( 6),15,0xa3014314L);
1128         R3(B,C,D,A,X(13),21,0x4e0811a1L);
1129         R3(A,B,C,D,X( 4), 6,0xf7537e82L);
1130         R3(D,A,B,C,X(11),10,0xbd3af235L);
1131         R3(C,D,A,B,X( 2),15,0x2ad7d2bbL);
1132         R3(B,C,D,A,X( 9),21,0xeb86d391L);
1133 
1134         A = c->A += A;
1135         B = c->B += B;
1136         C = c->C += C;
1137         D = c->D += D;
1138     }
1139 }
1140 #endif
1141 
1142 
1143 // ***************************************************************************
1144 #if COMPILER_LIKES_PRAGMA_MARK
1145 #pragma mark - base64 -> binary conversion
1146 #endif
1147 
1148 static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1149 static const char Pad64 = '=';
1150 
1151 
1152 #define mDNSisspace(x) (x == '\t' || x == '\n' || x == '\v' || x == '\f' || x == '\r' || x == ' ')
1153 
1154 mDNSlocal const char *mDNSstrchr(const char *s, int c)
1155 {
1156     while (1)
1157     {
1158         if (c == *s) return s;
1159         if (!*s) return mDNSNULL;
1160         s++;
1161     }
1162 }
1163 
1164 // skips all whitespace anywhere.
1165 // converts characters, four at a time, starting at (or after)
1166 // src from base - 64 numbers into three 8 bit bytes in the target area.
1167 // it returns the number of data bytes stored at the target, or -1 on error.
1168 // adapted from BIND sources
1169 
1170 mDNSlocal mDNSs32 DNSDigest_Base64ToBin(const char *src, mDNSu8 *target, mDNSu32 targsize)
1171 {
1172     int tarindex, state, ch;
1173     const char *pos;
1174 
1175     state = 0;
1176     tarindex = 0;
1177 
1178     while ((ch = *src++) != '\0') {
1179         if (mDNSisspace(ch))    /* Skip whitespace anywhere. */
1180             continue;
1181 
1182         if (ch == Pad64)
1183             break;
1184 
1185         pos = mDNSstrchr(Base64, ch);
1186         if (pos == 0)       /* A non-base64 character. */
1187             return (-1);
1188 
1189         switch (state) {
1190         case 0:
1191             if (target) {
1192                 if ((mDNSu32)tarindex >= targsize)
1193                     return (-1);
1194                 target[tarindex] = (mDNSu8)((pos - Base64) << 2);
1195             }
1196             state = 1;
1197             break;
1198         case 1:
1199             if (target) {
1200                 if ((mDNSu32)tarindex + 1 >= targsize)
1201                     return (-1);
1202                 target[tarindex]   |=  (pos - Base64) >> 4;
1203                 target[tarindex+1]  = (mDNSu8)(((pos - Base64) & 0x0f) << 4);
1204             }
1205             tarindex++;
1206             state = 2;
1207             break;
1208         case 2:
1209             if (target) {
1210                 if ((mDNSu32)tarindex + 1 >= targsize)
1211                     return (-1);
1212                 target[tarindex]   |=  (pos - Base64) >> 2;
1213                 target[tarindex+1]  = (mDNSu8)(((pos - Base64) & 0x03) << 6);
1214             }
1215             tarindex++;
1216             state = 3;
1217             break;
1218         case 3:
1219             if (target) {
1220                 if ((mDNSu32)tarindex >= targsize)
1221                     return (-1);
1222                 target[tarindex] |= (pos - Base64);
1223             }
1224             tarindex++;
1225             state = 0;
1226             break;
1227         default:
1228             return -1;
1229         }
1230     }
1231 
1232     /*
1233      * We are done decoding Base-64 chars.  Let's see if we ended
1234      * on a byte boundary, and/or with erroneous trailing characters.
1235      */
1236 
1237     if (ch == Pad64) {      /* We got a pad char. */
1238         ch = *src++;        /* Skip it, get next. */
1239         switch (state) {
1240         case 0:     /* Invalid = in first position */
1241         case 1:     /* Invalid = in second position */
1242             return (-1);
1243 
1244         case 2:     /* Valid, means one byte of info */
1245             /* Skip any number of spaces. */
1246             for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1247                 if (!mDNSisspace(ch))
1248                     break;
1249             /* Make sure there is another trailing = sign. */
1250             if (ch != Pad64)
1251                 return (-1);
1252             ch = *src++;        /* Skip the = */
1253         /* Fall through to "single trailing =" case. */
1254         /* FALLTHROUGH */
1255 
1256         case 3:     /* Valid, means two bytes of info */
1257             /*
1258              * We know this char is an =.  Is there anything but
1259              * whitespace after it?
1260              */
1261             for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1262                 if (!mDNSisspace(ch))
1263                     return (-1);
1264 
1265             /*
1266              * Now make sure for cases 2 and 3 that the "extra"
1267              * bits that slopped past the last full byte were
1268              * zeros.  If we don't check them, they become a
1269              * subliminal channel.
1270              */
1271             if (target && target[tarindex] != 0)
1272                 return (-1);
1273         }
1274     } else {
1275         /*
1276          * We ended by seeing the end of the string.  Make sure we
1277          * have no partial bytes lying around.
1278          */
1279         if (state != 0)
1280             return (-1);
1281     }
1282 
1283     return (tarindex);
1284 }
1285 
1286 
1287 // ***************************************************************************
1288 #if COMPILER_LIKES_PRAGMA_MARK
1289 #pragma mark - API exported to mDNS Core
1290 #endif
1291 
1292 // Constants
1293 #define HMAC_IPAD   0x36
1294 #define HMAC_OPAD   0x5c
1295 #define MD5_LEN     16
1296 
1297 #define HMAC_MD5_AlgName "\010" "hmac-md5" "\007" "sig-alg" "\003" "reg" "\003" "int"
1298 
1299 // Adapted from Appendix, RFC 2104
1300 mDNSlocal void DNSDigest_ConstructHMACKey(DomainAuthInfo *info, const mDNSu8 *key, mDNSu32 len)
1301 {
1302     MD5_CTX k;
1303     mDNSu8 buf[MD5_LEN];
1304     int i;
1305 
1306     // If key is longer than HMAC_LEN reset it to MD5(key)
1307     if (len > HMAC_LEN)
1308     {
1309         MD5_Init(&k);
1310         MD5_Update(&k, key, len);
1311         MD5_Final(buf, &k);
1312         key = buf;
1313         len = MD5_LEN;
1314     }
1315 
1316     // store key in pads
1317     mDNSPlatformMemZero(info->keydata_ipad, HMAC_LEN);
1318     mDNSPlatformMemZero(info->keydata_opad, HMAC_LEN);
1319     mDNSPlatformMemCopy(info->keydata_ipad, key, len);
1320     mDNSPlatformMemCopy(info->keydata_opad, key, len);
1321 
1322     // XOR key with ipad and opad values
1323     for (i = 0; i < HMAC_LEN; i++)
1324     {
1325         info->keydata_ipad[i] ^= HMAC_IPAD;
1326         info->keydata_opad[i] ^= HMAC_OPAD;
1327     }
1328 
1329 }
1330 
1331 mDNSexport mDNSs32 DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo *info, const char *b64key)
1332 {
1333     mDNSu8 keybuf[1024];
1334     mDNSs32 keylen = DNSDigest_Base64ToBin(b64key, keybuf, sizeof(keybuf));
1335     if (keylen < 0) return(keylen);
1336     DNSDigest_ConstructHMACKey(info, keybuf, (mDNSu32)keylen);
1337     return(keylen);
1338 }
1339 
1340 mDNSexport void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode)
1341 {
1342     AuthRecord tsig;
1343     mDNSu8  *rdata, *const countPtr = (mDNSu8 *)&msg->h.numAdditionals; // Get existing numAdditionals value
1344     mDNSu32 utc32;
1345     mDNSu8 utc48[6];
1346     mDNSu8 digest[MD5_LEN];
1347     mDNSu8 *ptr = *end;
1348     mDNSu32 len;
1349     mDNSOpaque16 buf;
1350     MD5_CTX c;
1351     mDNSu16 numAdditionals = (mDNSu16)((mDNSu16)countPtr[0] << 8 | countPtr[1]);
1352 
1353     // Init MD5 context, digest inner key pad and message
1354     MD5_Init(&c);
1355     MD5_Update(&c, info->keydata_ipad, HMAC_LEN);
1356     MD5_Update(&c, (mDNSu8 *)msg, (unsigned long)(*end - (mDNSu8 *)msg));
1357 
1358     // Construct TSIG RR, digesting variables as apporpriate
1359     mDNS_SetupResourceRecord(&tsig, mDNSNULL, 0, kDNSType_TSIG, 0, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
1360 
1361     // key name
1362     AssignDomainName(&tsig.namestorage, &info->keyname);
1363     MD5_Update(&c, info->keyname.c, DomainNameLength(&info->keyname));
1364 
1365     // class
1366     tsig.resrec.rrclass = kDNSQClass_ANY;
1367     buf = mDNSOpaque16fromIntVal(kDNSQClass_ANY);
1368     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1369 
1370     // ttl
1371     tsig.resrec.rroriginalttl = 0;
1372     MD5_Update(&c, (mDNSu8 *)&tsig.resrec.rroriginalttl, sizeof(tsig.resrec.rroriginalttl));
1373 
1374     // alg name
1375     AssignConstStringDomainName(&tsig.resrec.rdata->u.name, HMAC_MD5_AlgName);
1376     len = DomainNameLengthLimit((domainname *)HMAC_MD5_AlgName, (mDNSu8 *)HMAC_MD5_AlgName + sizeof HMAC_MD5_AlgName);
1377     rdata = tsig.resrec.rdata->u.data + len;
1378     MD5_Update(&c, (mDNSu8 *)HMAC_MD5_AlgName, len);
1379 
1380     // time
1381     // get UTC (universal time), convert to 48-bit unsigned in network byte order
1382     utc32 = (mDNSu32)mDNSPlatformUTC();
1383     if (utc32 == (unsigned)-1) { LogMsg("ERROR: DNSDigest_SignMessage - mDNSPlatformUTC returned bad time -1"); *end = mDNSNULL; }
1384     utc48[0] = 0;
1385     utc48[1] = 0;
1386     utc48[2] = (mDNSu8)((utc32 >> 24) & 0xff);
1387     utc48[3] = (mDNSu8)((utc32 >> 16) & 0xff);
1388     utc48[4] = (mDNSu8)((utc32 >>  8) & 0xff);
1389     utc48[5] = (mDNSu8)( utc32        & 0xff);
1390 
1391     mDNSPlatformMemCopy(rdata, utc48, 6);
1392     rdata += 6;
1393     MD5_Update(&c, utc48, 6);
1394 
1395     // 300 sec is fudge recommended in RFC 2485
1396     rdata[0] = (mDNSu8)((300 >> 8)  & 0xff);
1397     rdata[1] = (mDNSu8)( 300        & 0xff);
1398     MD5_Update(&c, rdata, sizeof(mDNSOpaque16));
1399     rdata += sizeof(mDNSOpaque16);
1400 
1401     // digest error (tcode) and other data len (zero) - we'll add them to the rdata later
1402     buf.b[0] = (mDNSu8)((tcode >> 8) & 0xff);
1403     buf.b[1] = (mDNSu8)( tcode       & 0xff);
1404     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // error
1405     buf.NotAnInteger = 0;
1406     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // other data len
1407 
1408     // finish the message & tsig var hash
1409     MD5_Final(digest, &c);
1410 
1411     // perform outer MD5 (outer key pad, inner digest)
1412     MD5_Init(&c);
1413     MD5_Update(&c, info->keydata_opad, HMAC_LEN);
1414     MD5_Update(&c, digest, MD5_LEN);
1415     MD5_Final(digest, &c);
1416 
1417     // set remaining rdata fields
1418     rdata[0] = (mDNSu8)((MD5_LEN >> 8)  & 0xff);
1419     rdata[1] = (mDNSu8)( MD5_LEN        & 0xff);
1420     rdata += sizeof(mDNSOpaque16);
1421     mDNSPlatformMemCopy(rdata, digest, MD5_LEN);                          // MAC
1422     rdata += MD5_LEN;
1423     rdata[0] = msg->h.id.b[0];                                            // original ID
1424     rdata[1] = msg->h.id.b[1];
1425     rdata[2] = (mDNSu8)((tcode >> 8) & 0xff);
1426     rdata[3] = (mDNSu8)( tcode       & 0xff);
1427     rdata[4] = 0;                                                         // other data len
1428     rdata[5] = 0;
1429     rdata += 6;
1430 
1431     tsig.resrec.rdlength = (mDNSu16)(rdata - tsig.resrec.rdata->u.data);
1432     *end = PutResourceRecordTTLJumbo(msg, ptr, &numAdditionals, &tsig.resrec, 0);
1433     if (!*end) { LogMsg("ERROR: DNSDigest_SignMessage - could not put TSIG"); *end = mDNSNULL; return; }
1434 
1435     // Write back updated numAdditionals value
1436     countPtr[0] = (mDNSu8)(numAdditionals >> 8);
1437     countPtr[1] = (mDNSu8)(numAdditionals &  0xFF);
1438 }
1439 
1440 mDNSexport mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord * lcr, DomainAuthInfo *info, mDNSu16 * rcode, mDNSu16 * tcode)
1441 {
1442     mDNSu8          *   ptr = (mDNSu8*) &lcr->r.resrec.rdata->u.data;
1443     mDNSs32 now;
1444     mDNSs32 then;
1445     mDNSu8 thisDigest[MD5_LEN];
1446     mDNSu8 thatDigest[MD5_LEN];
1447     mDNSOpaque16 buf;
1448     mDNSu8 utc48[6];
1449     mDNSs32 delta;
1450     mDNSu16 fudge;
1451     domainname      *   algo;
1452     MD5_CTX c;
1453     mDNSBool ok = mDNSfalse;
1454 
1455     // We only support HMAC-MD5 for now
1456 
1457     algo = (domainname*) ptr;
1458 
1459     if (!SameDomainName(algo, (domainname *)HMAC_MD5_AlgName))
1460     {
1461         LogMsg("ERROR: DNSDigest_VerifyMessage - TSIG algorithm not supported: %##s", algo->c);
1462         *rcode = kDNSFlag1_RC_NotAuth;
1463         *tcode = TSIG_ErrBadKey;
1464         ok = mDNSfalse;
1465         goto exit;
1466     }
1467 
1468     ptr += DomainNameLength(algo);
1469 
1470     // Check the times
1471 
1472     now = mDNSPlatformUTC();
1473     if (now == -1)
1474     {
1475         LogMsg("ERROR: DNSDigest_VerifyMessage - mDNSPlatformUTC returned bad time -1");
1476         *rcode = kDNSFlag1_RC_NotAuth;
1477         *tcode = TSIG_ErrBadTime;
1478         ok = mDNSfalse;
1479         goto exit;
1480     }
1481 
1482     // Get the 48 bit time field, skipping over the first word
1483 
1484     utc48[0] = *ptr++;
1485     utc48[1] = *ptr++;
1486     utc48[2] = *ptr++;
1487     utc48[3] = *ptr++;
1488     utc48[4] = *ptr++;
1489     utc48[5] = *ptr++;
1490 
1491     then  = (mDNSs32)NToH32(utc48 + sizeof(mDNSu16));
1492 
1493     fudge = NToH16(ptr);
1494 
1495     ptr += sizeof(mDNSu16);
1496 
1497     delta = (now > then) ? now - then : then - now;
1498 
1499     if (delta > fudge)
1500     {
1501         LogMsg("ERROR: DNSDigest_VerifyMessage - time skew > %d", fudge);
1502         *rcode = kDNSFlag1_RC_NotAuth;
1503         *tcode = TSIG_ErrBadTime;
1504         ok = mDNSfalse;
1505         goto exit;
1506     }
1507 
1508     // MAC size
1509 
1510     ptr += sizeof(mDNSu16);
1511 
1512     // MAC
1513 
1514     mDNSPlatformMemCopy(thatDigest, ptr, MD5_LEN);
1515 
1516     // Init MD5 context, digest inner key pad and message
1517 
1518     MD5_Init(&c);
1519     MD5_Update(&c, info->keydata_ipad, HMAC_LEN);
1520     MD5_Update(&c, (mDNSu8*) msg, (unsigned long)(end - (mDNSu8*) msg));
1521 
1522     // Key name
1523 
1524     MD5_Update(&c, lcr->r.resrec.name->c, DomainNameLength(lcr->r.resrec.name));
1525 
1526     // Class name
1527 
1528     buf = mDNSOpaque16fromIntVal(lcr->r.resrec.rrclass);
1529     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1530 
1531     // TTL
1532 
1533     MD5_Update(&c, (mDNSu8*) &lcr->r.resrec.rroriginalttl, sizeof(lcr->r.resrec.rroriginalttl));
1534 
1535     // Algorithm
1536 
1537     MD5_Update(&c, algo->c, DomainNameLength(algo));
1538 
1539     // Time
1540 
1541     MD5_Update(&c, utc48, 6);
1542 
1543     // Fudge
1544 
1545     buf = mDNSOpaque16fromIntVal(fudge);
1546     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1547 
1548     // Digest error and other data len (both zero) - we'll add them to the rdata later
1549 
1550     buf.NotAnInteger = 0;
1551     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // error
1552     MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));  // other data len
1553 
1554     // Finish the message & tsig var hash
1555 
1556     MD5_Final(thisDigest, &c);
1557 
1558     // perform outer MD5 (outer key pad, inner digest)
1559 
1560     MD5_Init(&c);
1561     MD5_Update(&c, info->keydata_opad, HMAC_LEN);
1562     MD5_Update(&c, thisDigest, MD5_LEN);
1563     MD5_Final(thisDigest, &c);
1564 
1565     if (!mDNSPlatformMemSame(thisDigest, thatDigest, MD5_LEN))
1566     {
1567         LogMsg("ERROR: DNSDigest_VerifyMessage - bad signature");
1568         *rcode = kDNSFlag1_RC_NotAuth;
1569         *tcode = TSIG_ErrBadSig;
1570         ok = mDNSfalse;
1571         goto exit;
1572     }
1573 
1574     // set remaining rdata fields
1575     ok = mDNStrue;
1576 
1577 exit:
1578 
1579     return ok;
1580 }
1581 
1582 
1583 #ifdef __cplusplus
1584 }
1585 #endif
1586