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