]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/DNSDigest.c
mDNSResponder-333.10.tar.gz
[apple/mdnsresponder.git] / mDNSCore / DNSDigest.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2011 Apple Computer, Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
22
23 #include "mDNSEmbeddedAPI.h"
24 #include "DNSCommon.h"
25
26 // Disable certain benign warnings with Microsoft compilers
27 #if(defined(_MSC_VER))
28 // Disable "conditional expression is constant" warning for debug macros.
29 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
30 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
31 #pragma warning(disable:4127)
32 #endif
33
34
35 // ***************************************************************************
36 #if COMPILER_LIKES_PRAGMA_MARK
37 #pragma mark - Byte Swapping Functions
38 #endif
39
40 mDNSlocal mDNSu16 NToH16(mDNSu8 * bytes)
41 {
42 return (mDNSu16)((mDNSu16)bytes[0] << 8 | (mDNSu16)bytes[1]);
43 }
44
45 mDNSlocal mDNSu32 NToH32(mDNSu8 * bytes)
46 {
47 return (mDNSu32)((mDNSu32) bytes[0] << 24 | (mDNSu32) bytes[1] << 16 | (mDNSu32) bytes[2] << 8 | (mDNSu32)bytes[3]);
48 }
49
50 // ***************************************************************************
51 #if COMPILER_LIKES_PRAGMA_MARK
52 #pragma mark - MD5 Hash Functions
53 #endif
54
55
56 /* The source for the has is derived CommonCrypto files CommonDigest.h, md32_common.h, md5_locl.h, md5_locl.h, and openssl/md5.h.
57 * The following changes have been made to the original sources:
58 * replaced CC_LONG w/ mDNSu32
59 * replaced CC_MD5* with MD5*
60 * replaced CC_LONG w/ mDNSu32, removed conditional #defines from md5.h
61 * removed extern decls for MD5_Init/Update/Final from CommonDigest.h
62 * removed APPLE_COMMON_DIGEST specific #defines from md5_locl.h
63 *
64 * Note: machine archetecure specific conditionals from the original sources are turned off, but are left in the code
65 * to aid in platform-specific optimizations and debugging.
66 * Sources originally distributed under the following license headers:
67 * CommonDigest.h - APSL
68 *
69 * md32_Common.h
70 * ====================================================================
71 * Copyright (c) 1999-2002 The OpenSSL Project. All rights reserved.
72 *
73 * Redistribution and use in source and binary forms, with or without
74 * modification, are permitted provided that the following conditions
75 * are met:
76 *
77 * 1. Redistributions of source code must retain the above copyright
78 * notice, this list of conditions and the following disclaimer.
79 *
80 * 2. Redistributions in binary form must reproduce the above copyright
81 * notice, this list of conditions and the following disclaimer in
82 * the documentation and/or other materials provided with the
83 * distribution.
84 *
85 * 3. All advertising materials mentioning features or use of this
86 * software must display the following acknowledgment:
87 * "This product includes software developed by the OpenSSL Project
88 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
89 *
90 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
91 * endorse or promote products derived from this software without
92 * prior written permission. For written permission, please contact
93 * licensing@OpenSSL.org.
94 *
95 * 5. Products derived from this software may not be called "OpenSSL"
96 * nor may "OpenSSL" appear in their names without prior written
97 * permission of the OpenSSL Project.
98 *
99 * 6. Redistributions of any form whatsoever must retain the following
100 * acknowledgment:
101 * "This product includes software developed by the OpenSSL Project
102 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
103 *
104 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
105 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
106 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
107 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
108 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
109 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
110 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
111 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
112 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
113 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
114 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
115 * OF THE POSSIBILITY OF SUCH DAMAGE.
116 *
117 *
118 * md5_dgst.c, md5_locl.h
119 * ====================================================================
120 *
121 * This product includes cryptographic software written by Eric Young
122 * (eay@cryptsoft.com). This product includes software written by Tim
123 * Hudson (tjh@cryptsoft.com).
124 *
125 * Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
126 * All rights reserved.
127 *
128 * This package is an SSL implementation written
129 * by Eric Young (eay@cryptsoft.com).
130 * The implementation was written so as to conform with Netscapes SSL.
131 *
132 * This library is free for commercial and non-commercial use as long as
133 * the following conditions are aheared to. The following conditions
134 * apply to all code found in this distribution, be it the RC4, RSA,
135 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
136 * included with this distribution is covered by the same copyright terms
137 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
138 *
139 * Copyright remains Eric Young's, and as such any Copyright notices in
140 * the code are not to be removed.
141 * If this package is used in a product, Eric Young should be given attribution
142 * as the author of the parts of the library used.
143 * This can be in the form of a textual message at program startup or
144 * in documentation (online or textual) provided with the package.
145 *
146 * Redistribution and use in source and binary forms, with or without
147 * modification, are permitted provided that the following conditions
148 * are met:
149 * 1. Redistributions of source code must retain the copyright
150 * notice, this list of conditions and the following disclaimer.
151 * 2. Redistributions in binary form must reproduce the above copyright
152 * notice, this list of conditions and the following disclaimer in the
153 * documentation and/or other materials provided with the distribution.
154 * 3. All advertising materials mentioning features or use of this software
155 * must display the following acknowledgement:
156 * "This product includes cryptographic software written by
157 * Eric Young (eay@cryptsoft.com)"
158 * The word 'cryptographic' can be left out if the rouines from the library
159 * being used are not cryptographic related :-).
160 * 4. If you include any Windows specific code (or a derivative thereof) from
161 * the apps directory (application code) you must include an acknowledgement:
162 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
163 *
164 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
165 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
166 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
167 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
168 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
169 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
170 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
171 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
172 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
173 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
174 * SUCH DAMAGE.
175 *
176 * The licence and distribution terms for any publically available version or
177 * derivative of this code cannot be changed. i.e. this code cannot simply be
178 * copied and put under another distribution licence
179 * [including the GNU Public Licence.]
180 *
181 */
182
183 //from CommonDigest.h
184
185 #define MD5_DIGEST_LENGTH 16 /* digest length in bytes */
186 #define MD5_BLOCK_BYTES 64 /* block size in bytes */
187 #define MD5_BLOCK_LONG (MD5_BLOCK_BYTES / sizeof(mDNSu32))
188
189 typedef struct MD5state_st
190 {
191 mDNSu32 A,B,C,D;
192 mDNSu32 Nl,Nh;
193 mDNSu32 data[MD5_BLOCK_LONG];
194 int num;
195 } MD5_CTX;
196
197
198 // from openssl/md5.h
199
200 #define MD5_CBLOCK 64
201 #define MD5_LBLOCK (MD5_CBLOCK/4)
202 #define MD5_DIGEST_LENGTH 16
203
204 int MD5_Init(MD5_CTX *c);
205 int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
206 int MD5_Final(unsigned char *md, MD5_CTX *c);
207 void MD5_Transform(MD5_CTX *c, const unsigned char *b);
208
209 // From md5_locl.h
210
211 #ifndef MD5_LONG_LOG2
212 #define MD5_LONG_LOG2 2 /* default to 32 bits */
213 #endif
214
215 #ifdef MD5_ASM
216 # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__)
217 # define md5_block_host_order md5_block_asm_host_order
218 # elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
219 void md5_block_asm_data_order_aligned (MD5_CTX *c, const mDNSu32 *p,int num);
220 # define HASH_BLOCK_DATA_ORDER_ALIGNED md5_block_asm_data_order_aligned
221 # endif
222 #endif
223
224 void md5_block_host_order (MD5_CTX *c, const void *p,int num);
225 void md5_block_data_order (MD5_CTX *c, const void *p,int num);
226
227 #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__)
228 /*
229 * *_block_host_order is expected to handle aligned data while
230 * *_block_data_order - unaligned. As algorithm and host (x86)
231 * are in this case of the same "endianness" these two are
232 * otherwise indistinguishable. But normally you don't want to
233 * call the same function because unaligned access in places
234 * where alignment is expected is usually a "Bad Thing". Indeed,
235 * on RISCs you get punished with BUS ERROR signal or *severe*
236 * performance degradation. Intel CPUs are in turn perfectly
237 * capable of loading unaligned data without such drastic side
238 * effect. Yes, they say it's slower than aligned load, but no
239 * exception is generated and therefore performance degradation
240 * is *incomparable* with RISCs. What we should weight here is
241 * costs of unaligned access against costs of aligning data.
242 * According to my measurements allowing unaligned access results
243 * in ~9% performance improvement on Pentium II operating at
244 * 266MHz. I won't be surprised if the difference will be higher
245 * on faster systems:-)
246 *
247 * <appro@fy.chalmers.se>
248 */
249 #define md5_block_data_order md5_block_host_order
250 #endif
251
252 #define DATA_ORDER_IS_LITTLE_ENDIAN
253
254 #define HASH_LONG mDNSu32
255 #define HASH_LONG_LOG2 MD5_LONG_LOG2
256 #define HASH_CTX MD5_CTX
257 #define HASH_CBLOCK MD5_CBLOCK
258 #define HASH_LBLOCK MD5_LBLOCK
259
260 #define HASH_UPDATE MD5_Update
261 #define HASH_TRANSFORM MD5_Transform
262 #define HASH_FINAL MD5_Final
263
264 #define HASH_MAKE_STRING(c,s) do { \
265 unsigned long ll; \
266 ll=(c)->A; HOST_l2c(ll,(s)); \
267 ll=(c)->B; HOST_l2c(ll,(s)); \
268 ll=(c)->C; HOST_l2c(ll,(s)); \
269 ll=(c)->D; HOST_l2c(ll,(s)); \
270 } while (0)
271 #define HASH_BLOCK_HOST_ORDER md5_block_host_order
272 #if !defined(L_ENDIAN) || defined(md5_block_data_order)
273 #define HASH_BLOCK_DATA_ORDER md5_block_data_order
274 /*
275 * Little-endians (Intel and Alpha) feel better without this.
276 * It looks like memcpy does better job than generic
277 * md5_block_data_order on copying-n-aligning input data.
278 * But frankly speaking I didn't expect such result on Alpha.
279 * On the other hand I've got this with egcs-1.0.2 and if
280 * program is compiled with another (better?) compiler it
281 * might turn out other way around.
282 *
283 * <appro@fy.chalmers.se>
284 */
285 #endif
286
287
288 // from md32_common.h
289
290 /*
291 * This is a generic 32 bit "collector" for message digest algorithms.
292 * Whenever needed it collects input character stream into chunks of
293 * 32 bit values and invokes a block function that performs actual hash
294 * calculations.
295 *
296 * Porting guide.
297 *
298 * Obligatory macros:
299 *
300 * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
301 * this macro defines byte order of input stream.
302 * HASH_CBLOCK
303 * size of a unit chunk HASH_BLOCK operates on.
304 * HASH_LONG
305 * has to be at lest 32 bit wide, if it's wider, then
306 * HASH_LONG_LOG2 *has to* be defined along
307 * HASH_CTX
308 * context structure that at least contains following
309 * members:
310 * typedef struct {
311 * ...
312 * HASH_LONG Nl,Nh;
313 * HASH_LONG data[HASH_LBLOCK];
314 * int num;
315 * ...
316 * } HASH_CTX;
317 * HASH_UPDATE
318 * name of "Update" function, implemented here.
319 * HASH_TRANSFORM
320 * name of "Transform" function, implemented here.
321 * HASH_FINAL
322 * name of "Final" function, implemented here.
323 * HASH_BLOCK_HOST_ORDER
324 * name of "block" function treating *aligned* input message
325 * in host byte order, implemented externally.
326 * HASH_BLOCK_DATA_ORDER
327 * name of "block" function treating *unaligned* input message
328 * in original (data) byte order, implemented externally (it
329 * actually is optional if data and host are of the same
330 * "endianess").
331 * HASH_MAKE_STRING
332 * macro convering context variables to an ASCII hash string.
333 *
334 * Optional macros:
335 *
336 * B_ENDIAN or L_ENDIAN
337 * defines host byte-order.
338 * HASH_LONG_LOG2
339 * defaults to 2 if not states otherwise.
340 * HASH_LBLOCK
341 * assumed to be HASH_CBLOCK/4 if not stated otherwise.
342 * HASH_BLOCK_DATA_ORDER_ALIGNED
343 * alternative "block" function capable of treating
344 * aligned input message in original (data) order,
345 * implemented externally.
346 *
347 * MD5 example:
348 *
349 * #define DATA_ORDER_IS_LITTLE_ENDIAN
350 *
351 * #define HASH_LONG mDNSu32
352 * #define HASH_LONG_LOG2 mDNSu32_LOG2
353 * #define HASH_CTX MD5_CTX
354 * #define HASH_CBLOCK MD5_CBLOCK
355 * #define HASH_LBLOCK MD5_LBLOCK
356 * #define HASH_UPDATE MD5_Update
357 * #define HASH_TRANSFORM MD5_Transform
358 * #define HASH_FINAL MD5_Final
359 * #define HASH_BLOCK_HOST_ORDER md5_block_host_order
360 * #define HASH_BLOCK_DATA_ORDER md5_block_data_order
361 *
362 * <appro@fy.chalmers.se>
363 */
364
365 #if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
366 #error "DATA_ORDER must be defined!"
367 #endif
368
369 #ifndef HASH_CBLOCK
370 #error "HASH_CBLOCK must be defined!"
371 #endif
372 #ifndef HASH_LONG
373 #error "HASH_LONG must be defined!"
374 #endif
375 #ifndef HASH_CTX
376 #error "HASH_CTX must be defined!"
377 #endif
378
379 #ifndef HASH_UPDATE
380 #error "HASH_UPDATE must be defined!"
381 #endif
382 #ifndef HASH_TRANSFORM
383 #error "HASH_TRANSFORM must be defined!"
384 #endif
385 #ifndef HASH_FINAL
386 #error "HASH_FINAL must be defined!"
387 #endif
388
389 #ifndef HASH_BLOCK_HOST_ORDER
390 #error "HASH_BLOCK_HOST_ORDER must be defined!"
391 #endif
392
393 #if 0
394 /*
395 * Moved below as it's required only if HASH_BLOCK_DATA_ORDER_ALIGNED
396 * isn't defined.
397 */
398 #ifndef HASH_BLOCK_DATA_ORDER
399 #error "HASH_BLOCK_DATA_ORDER must be defined!"
400 #endif
401 #endif
402
403 #ifndef HASH_LBLOCK
404 #define HASH_LBLOCK (HASH_CBLOCK/4)
405 #endif
406
407 #ifndef HASH_LONG_LOG2
408 #define HASH_LONG_LOG2 2
409 #endif
410
411 /*
412 * Engage compiler specific rotate intrinsic function if available.
413 */
414 #undef ROTATE
415 #ifndef PEDANTIC
416 # if 0 /* defined(_MSC_VER) */
417 # define ROTATE(a,n) _lrotl(a,n)
418 # elif defined(__MWERKS__)
419 # if defined(__POWERPC__)
420 # define ROTATE(a,n) (unsigned MD32_REG_T)__rlwinm((int)a,n,0,31)
421 # elif defined(__MC68K__)
422 /* Motorola specific tweak. <appro@fy.chalmers.se> */
423 # define ROTATE(a,n) (n<24 ? __rol(a,n) : __ror(a,32-n))
424 # else
425 # define ROTATE(a,n) __rol(a,n)
426 # endif
427 # elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
428 /*
429 * Some GNU C inline assembler templates. Note that these are
430 * rotates by *constant* number of bits! But that's exactly
431 * what we need here...
432 *
433 * <appro@fy.chalmers.se>
434 */
435 /*
436 * LLVM is more strict about compatibility of types between input & output constraints,
437 * but we want these to be rotations of 32 bits, not 64, so we explicitly drop the
438 * most significant bytes by casting to an unsigned int.
439 */
440 # if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
441 # define ROTATE(a,n) ({ register unsigned int ret; \
442 asm ( \
443 "roll %1,%0" \
444 : "=r"(ret) \
445 : "I"(n), "0"((unsigned int)a) \
446 : "cc"); \
447 ret; \
448 })
449 # elif defined(__powerpc) || defined(__ppc)
450 # define ROTATE(a,n) ({ register unsigned int ret; \
451 asm ( \
452 "rlwinm %0,%1,%2,0,31" \
453 : "=r"(ret) \
454 : "r"(a), "I"(n)); \
455 ret; \
456 })
457 # endif
458 # endif
459
460 /*
461 * Engage compiler specific "fetch in reverse byte order"
462 * intrinsic function if available.
463 */
464 # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
465 /* some GNU C inline assembler templates by <appro@fy.chalmers.se> */
466 # if (defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)) && !defined(I386_ONLY)
467 # define BE_FETCH32(a) ({ register unsigned int l=(a);\
468 asm ( \
469 "bswapl %0" \
470 : "=r"(l) : "0"(l)); \
471 l; \
472 })
473 # elif defined(__powerpc)
474 # define LE_FETCH32(a) ({ register unsigned int l; \
475 asm ( \
476 "lwbrx %0,0,%1" \
477 : "=r"(l) \
478 : "r"(a)); \
479 l; \
480 })
481
482 # elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
483 # define LE_FETCH32(a) ({ register unsigned int l; \
484 asm ( \
485 "lda [%1]#ASI_PRIMARY_LITTLE,%0"\
486 : "=r"(l) \
487 : "r"(a)); \
488 l; \
489 })
490 # endif
491 # endif
492 #endif /* PEDANTIC */
493
494 #if HASH_LONG_LOG2==2 /* Engage only if sizeof(HASH_LONG)== 4 */
495 /* A nice byte order reversal from Wei Dai <weidai@eskimo.com> */
496 #ifdef ROTATE
497 /* 5 instructions with rotate instruction, else 9 */
498 #define REVERSE_FETCH32(a,l) ( \
499 l=*(const HASH_LONG *)(a), \
500 ((ROTATE(l,8)&0x00FF00FF)|(ROTATE((l&0x00FF00FF),24))) \
501 )
502 #else
503 /* 6 instructions with rotate instruction, else 8 */
504 #define REVERSE_FETCH32(a,l) ( \
505 l=*(const HASH_LONG *)(a), \
506 l=(((l>>8)&0x00FF00FF)|((l&0x00FF00FF)<<8)), \
507 ROTATE(l,16) \
508 )
509 /*
510 * Originally the middle line started with l=(((l&0xFF00FF00)>>8)|...
511 * It's rewritten as above for two reasons:
512 * - RISCs aren't good at long constants and have to explicitely
513 * compose 'em with several (well, usually 2) instructions in a
514 * register before performing the actual operation and (as you
515 * already realized:-) having same constant should inspire the
516 * compiler to permanently allocate the only register for it;
517 * - most modern CPUs have two ALUs, but usually only one has
518 * circuitry for shifts:-( this minor tweak inspires compiler
519 * to schedule shift instructions in a better way...
520 *
521 * <appro@fy.chalmers.se>
522 */
523 #endif
524 #endif
525
526 #ifndef ROTATE
527 #define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
528 #endif
529
530 /*
531 * Make some obvious choices. E.g., HASH_BLOCK_DATA_ORDER_ALIGNED
532 * and HASH_BLOCK_HOST_ORDER ought to be the same if input data
533 * and host are of the same "endianess". It's possible to mask
534 * this with blank #define HASH_BLOCK_DATA_ORDER though...
535 *
536 * <appro@fy.chalmers.se>
537 */
538 #if defined(B_ENDIAN)
539 # if defined(DATA_ORDER_IS_BIG_ENDIAN)
540 # if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
541 # define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER
542 # endif
543 # elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
544 # ifndef HOST_FETCH32
545 # ifdef LE_FETCH32
546 # define HOST_FETCH32(p,l) LE_FETCH32(p)
547 # elif defined(REVERSE_FETCH32)
548 # define HOST_FETCH32(p,l) REVERSE_FETCH32(p,l)
549 # endif
550 # endif
551 # endif
552 #elif defined(L_ENDIAN)
553 # if defined(DATA_ORDER_IS_LITTLE_ENDIAN)
554 # if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
555 # define HASH_BLOCK_DATA_ORDER_ALIGNED HASH_BLOCK_HOST_ORDER
556 # endif
557 # elif defined(DATA_ORDER_IS_BIG_ENDIAN)
558 # ifndef HOST_FETCH32
559 # ifdef BE_FETCH32
560 # define HOST_FETCH32(p,l) BE_FETCH32(p)
561 # elif defined(REVERSE_FETCH32)
562 # define HOST_FETCH32(p,l) REVERSE_FETCH32(p,l)
563 # endif
564 # endif
565 # endif
566 #endif
567
568 #if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
569 #ifndef HASH_BLOCK_DATA_ORDER
570 #error "HASH_BLOCK_DATA_ORDER must be defined!"
571 #endif
572 #endif
573
574 // None of the invocations of the following macros actually use the result,
575 // so cast them to void to avoid any compiler warnings/errors about not using
576 // the result (e.g. when using clang).
577 // If the resultant values need to be used at some point, these must be changed.
578 #define HOST_c2l(c,l) ((void)_HOST_c2l(c,l))
579 #define HOST_l2c(l,c) ((void)_HOST_l2c(l,c))
580
581 #if defined(DATA_ORDER_IS_BIG_ENDIAN)
582
583 #define _HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \
584 l|=(((unsigned long)(*((c)++)))<<16), \
585 l|=(((unsigned long)(*((c)++)))<< 8), \
586 l|=(((unsigned long)(*((c)++))) ), \
587 l)
588 #define HOST_p_c2l(c,l,n) { \
589 switch (n) { \
590 case 0: l =((unsigned long)(*((c)++)))<<24; \
591 case 1: l|=((unsigned long)(*((c)++)))<<16; \
592 case 2: l|=((unsigned long)(*((c)++)))<< 8; \
593 case 3: l|=((unsigned long)(*((c)++))); \
594 } }
595 #define HOST_p_c2l_p(c,l,sc,len) { \
596 switch (sc) { \
597 case 0: l =((unsigned long)(*((c)++)))<<24; \
598 if (--len == 0) break; \
599 case 1: l|=((unsigned long)(*((c)++)))<<16; \
600 if (--len == 0) break; \
601 case 2: l|=((unsigned long)(*((c)++)))<< 8; \
602 } }
603 /* NOTE the pointer is not incremented at the end of this */
604 #define HOST_c2l_p(c,l,n) { \
605 l=0; (c)+=n; \
606 switch (n) { \
607 case 3: l =((unsigned long)(*(--(c))))<< 8; \
608 case 2: l|=((unsigned long)(*(--(c))))<<16; \
609 case 1: l|=((unsigned long)(*(--(c))))<<24; \
610 } }
611 #define _HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
612 *((c)++)=(unsigned char)(((l)>>16)&0xff), \
613 *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
614 *((c)++)=(unsigned char)(((l) )&0xff), \
615 l)
616
617 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
618
619 #define _HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \
620 l|=(((unsigned long)(*((c)++)))<< 8), \
621 l|=(((unsigned long)(*((c)++)))<<16), \
622 l|=(((unsigned long)(*((c)++)))<<24), \
623 l)
624 #define HOST_p_c2l(c,l,n) { \
625 switch (n) { \
626 case 0: l =((unsigned long)(*((c)++))); \
627 case 1: l|=((unsigned long)(*((c)++)))<< 8; \
628 case 2: l|=((unsigned long)(*((c)++)))<<16; \
629 case 3: l|=((unsigned long)(*((c)++)))<<24; \
630 } }
631 #define HOST_p_c2l_p(c,l,sc,len) { \
632 switch (sc) { \
633 case 0: l =((unsigned long)(*((c)++))); \
634 if (--len == 0) break; \
635 case 1: l|=((unsigned long)(*((c)++)))<< 8; \
636 if (--len == 0) break; \
637 case 2: l|=((unsigned long)(*((c)++)))<<16; \
638 } }
639 /* NOTE the pointer is not incremented at the end of this */
640 #define HOST_c2l_p(c,l,n) { \
641 l=0; (c)+=n; \
642 switch (n) { \
643 case 3: l =((unsigned long)(*(--(c))))<<16; \
644 case 2: l|=((unsigned long)(*(--(c))))<< 8; \
645 case 1: l|=((unsigned long)(*(--(c)))); \
646 } }
647 #define _HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \
648 *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
649 *((c)++)=(unsigned char)(((l)>>16)&0xff), \
650 *((c)++)=(unsigned char)(((l)>>24)&0xff), \
651 l)
652
653 #endif
654
655 /*
656 * Time for some action:-)
657 */
658
659 int HASH_UPDATE (HASH_CTX *c, const void *data_, unsigned long len)
660 {
661 const unsigned char *data=(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; 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; 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; 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 for (;num--;)
1059 {
1060 HOST_c2l(data,l); X( 0)=l; HOST_c2l(data,l); X( 1)=l;
1061 /* Round 0 */
1062 R0(A,B,C,D,X( 0), 7,0xd76aa478L); HOST_c2l(data,l); X( 2)=l;
1063 R0(D,A,B,C,X( 1),12,0xe8c7b756L); HOST_c2l(data,l); X( 3)=l;
1064 R0(C,D,A,B,X( 2),17,0x242070dbL); HOST_c2l(data,l); X( 4)=l;
1065 R0(B,C,D,A,X( 3),22,0xc1bdceeeL); HOST_c2l(data,l); X( 5)=l;
1066 R0(A,B,C,D,X( 4), 7,0xf57c0fafL); HOST_c2l(data,l); X( 6)=l;
1067 R0(D,A,B,C,X( 5),12,0x4787c62aL); HOST_c2l(data,l); X( 7)=l;
1068 R0(C,D,A,B,X( 6),17,0xa8304613L); HOST_c2l(data,l); X( 8)=l;
1069 R0(B,C,D,A,X( 7),22,0xfd469501L); HOST_c2l(data,l); X( 9)=l;
1070 R0(A,B,C,D,X( 8), 7,0x698098d8L); HOST_c2l(data,l); X(10)=l;
1071 R0(D,A,B,C,X( 9),12,0x8b44f7afL); HOST_c2l(data,l); X(11)=l;
1072 R0(C,D,A,B,X(10),17,0xffff5bb1L); HOST_c2l(data,l); X(12)=l;
1073 R0(B,C,D,A,X(11),22,0x895cd7beL); HOST_c2l(data,l); X(13)=l;
1074 R0(A,B,C,D,X(12), 7,0x6b901122L); HOST_c2l(data,l); X(14)=l;
1075 R0(D,A,B,C,X(13),12,0xfd987193L); HOST_c2l(data,l); X(15)=l;
1076 R0(C,D,A,B,X(14),17,0xa679438eL);
1077 R0(B,C,D,A,X(15),22,0x49b40821L);
1078 /* Round 1 */
1079 R1(A,B,C,D,X( 1), 5,0xf61e2562L);
1080 R1(D,A,B,C,X( 6), 9,0xc040b340L);
1081 R1(C,D,A,B,X(11),14,0x265e5a51L);
1082 R1(B,C,D,A,X( 0),20,0xe9b6c7aaL);
1083 R1(A,B,C,D,X( 5), 5,0xd62f105dL);
1084 R1(D,A,B,C,X(10), 9,0x02441453L);
1085 R1(C,D,A,B,X(15),14,0xd8a1e681L);
1086 R1(B,C,D,A,X( 4),20,0xe7d3fbc8L);
1087 R1(A,B,C,D,X( 9), 5,0x21e1cde6L);
1088 R1(D,A,B,C,X(14), 9,0xc33707d6L);
1089 R1(C,D,A,B,X( 3),14,0xf4d50d87L);
1090 R1(B,C,D,A,X( 8),20,0x455a14edL);
1091 R1(A,B,C,D,X(13), 5,0xa9e3e905L);
1092 R1(D,A,B,C,X( 2), 9,0xfcefa3f8L);
1093 R1(C,D,A,B,X( 7),14,0x676f02d9L);
1094 R1(B,C,D,A,X(12),20,0x8d2a4c8aL);
1095 /* Round 2 */
1096 R2(A,B,C,D,X( 5), 4,0xfffa3942L);
1097 R2(D,A,B,C,X( 8),11,0x8771f681L);
1098 R2(C,D,A,B,X(11),16,0x6d9d6122L);
1099 R2(B,C,D,A,X(14),23,0xfde5380cL);
1100 R2(A,B,C,D,X( 1), 4,0xa4beea44L);
1101 R2(D,A,B,C,X( 4),11,0x4bdecfa9L);
1102 R2(C,D,A,B,X( 7),16,0xf6bb4b60L);
1103 R2(B,C,D,A,X(10),23,0xbebfbc70L);
1104 R2(A,B,C,D,X(13), 4,0x289b7ec6L);
1105 R2(D,A,B,C,X( 0),11,0xeaa127faL);
1106 R2(C,D,A,B,X( 3),16,0xd4ef3085L);
1107 R2(B,C,D,A,X( 6),23,0x04881d05L);
1108 R2(A,B,C,D,X( 9), 4,0xd9d4d039L);
1109 R2(D,A,B,C,X(12),11,0xe6db99e5L);
1110 R2(C,D,A,B,X(15),16,0x1fa27cf8L);
1111 R2(B,C,D,A,X( 2),23,0xc4ac5665L);
1112 /* Round 3 */
1113 R3(A,B,C,D,X( 0), 6,0xf4292244L);
1114 R3(D,A,B,C,X( 7),10,0x432aff97L);
1115 R3(C,D,A,B,X(14),15,0xab9423a7L);
1116 R3(B,C,D,A,X( 5),21,0xfc93a039L);
1117 R3(A,B,C,D,X(12), 6,0x655b59c3L);
1118 R3(D,A,B,C,X( 3),10,0x8f0ccc92L);
1119 R3(C,D,A,B,X(10),15,0xffeff47dL);
1120 R3(B,C,D,A,X( 1),21,0x85845dd1L);
1121 R3(A,B,C,D,X( 8), 6,0x6fa87e4fL);
1122 R3(D,A,B,C,X(15),10,0xfe2ce6e0L);
1123 R3(C,D,A,B,X( 6),15,0xa3014314L);
1124 R3(B,C,D,A,X(13),21,0x4e0811a1L);
1125 R3(A,B,C,D,X( 4), 6,0xf7537e82L);
1126 R3(D,A,B,C,X(11),10,0xbd3af235L);
1127 R3(C,D,A,B,X( 2),15,0x2ad7d2bbL);
1128 R3(B,C,D,A,X( 9),21,0xeb86d391L);
1129
1130 A = c->A += A;
1131 B = c->B += B;
1132 C = c->C += C;
1133 D = c->D += D;
1134 }
1135 }
1136 #endif
1137
1138
1139 // ***************************************************************************
1140 #if COMPILER_LIKES_PRAGMA_MARK
1141 #pragma mark - base64 -> binary conversion
1142 #endif
1143
1144 static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1145 static const char Pad64 = '=';
1146
1147
1148 #define mDNSisspace(x) (x == '\t' || x == '\n' || x == '\v' || x == '\f' || x == '\r' || x == ' ')
1149
1150 mDNSlocal const char *mDNSstrchr(const char *s, int c)
1151 {
1152 while (1)
1153 {
1154 if (c == *s) return s;
1155 if (!*s) return mDNSNULL;
1156 s++;
1157 }
1158 }
1159
1160 // skips all whitespace anywhere.
1161 // converts characters, four at a time, starting at (or after)
1162 // src from base - 64 numbers into three 8 bit bytes in the target area.
1163 // it returns the number of data bytes stored at the target, or -1 on error.
1164 // adapted from BIND sources
1165
1166 mDNSlocal mDNSs32 DNSDigest_Base64ToBin(const char *src, mDNSu8 *target, mDNSu32 targsize)
1167 {
1168 int tarindex, state, ch;
1169 const char *pos;
1170
1171 state = 0;
1172 tarindex = 0;
1173
1174 while ((ch = *src++) != '\0') {
1175 if (mDNSisspace(ch)) /* Skip whitespace anywhere. */
1176 continue;
1177
1178 if (ch == Pad64)
1179 break;
1180
1181 pos = mDNSstrchr(Base64, ch);
1182 if (pos == 0) /* A non-base64 character. */
1183 return (-1);
1184
1185 switch (state) {
1186 case 0:
1187 if (target) {
1188 if ((mDNSu32)tarindex >= targsize)
1189 return (-1);
1190 target[tarindex] = (mDNSu8)((pos - Base64) << 2);
1191 }
1192 state = 1;
1193 break;
1194 case 1:
1195 if (target) {
1196 if ((mDNSu32)tarindex + 1 >= targsize)
1197 return (-1);
1198 target[tarindex] |= (pos - Base64) >> 4;
1199 target[tarindex+1] = (mDNSu8)(((pos - Base64) & 0x0f) << 4);
1200 }
1201 tarindex++;
1202 state = 2;
1203 break;
1204 case 2:
1205 if (target) {
1206 if ((mDNSu32)tarindex + 1 >= targsize)
1207 return (-1);
1208 target[tarindex] |= (pos - Base64) >> 2;
1209 target[tarindex+1] = (mDNSu8)(((pos - Base64) & 0x03) << 6);
1210 }
1211 tarindex++;
1212 state = 3;
1213 break;
1214 case 3:
1215 if (target) {
1216 if ((mDNSu32)tarindex >= targsize)
1217 return (-1);
1218 target[tarindex] |= (pos - Base64);
1219 }
1220 tarindex++;
1221 state = 0;
1222 break;
1223 default:
1224 return -1;
1225 }
1226 }
1227
1228 /*
1229 * We are done decoding Base-64 chars. Let's see if we ended
1230 * on a byte boundary, and/or with erroneous trailing characters.
1231 */
1232
1233 if (ch == Pad64) { /* We got a pad char. */
1234 ch = *src++; /* Skip it, get next. */
1235 switch (state) {
1236 case 0: /* Invalid = in first position */
1237 case 1: /* Invalid = in second position */
1238 return (-1);
1239
1240 case 2: /* Valid, means one byte of info */
1241 /* Skip any number of spaces. */
1242 for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1243 if (!mDNSisspace(ch))
1244 break;
1245 /* Make sure there is another trailing = sign. */
1246 if (ch != Pad64)
1247 return (-1);
1248 ch = *src++; /* Skip the = */
1249 /* Fall through to "single trailing =" case. */
1250 /* FALLTHROUGH */
1251
1252 case 3: /* Valid, means two bytes of info */
1253 /*
1254 * We know this char is an =. Is there anything but
1255 * whitespace after it?
1256 */
1257 for ((void)mDNSNULL; ch != '\0'; ch = *src++)
1258 if (!mDNSisspace(ch))
1259 return (-1);
1260
1261 /*
1262 * Now make sure for cases 2 and 3 that the "extra"
1263 * bits that slopped past the last full byte were
1264 * zeros. If we don't check them, they become a
1265 * subliminal channel.
1266 */
1267 if (target && target[tarindex] != 0)
1268 return (-1);
1269 }
1270 } else {
1271 /*
1272 * We ended by seeing the end of the string. Make sure we
1273 * have no partial bytes lying around.
1274 */
1275 if (state != 0)
1276 return (-1);
1277 }
1278
1279 return (tarindex);
1280 }
1281
1282
1283 // ***************************************************************************
1284 #if COMPILER_LIKES_PRAGMA_MARK
1285 #pragma mark - API exported to mDNS Core
1286 #endif
1287
1288 // Constants
1289 #define HMAC_IPAD 0x36
1290 #define HMAC_OPAD 0x5c
1291 #define MD5_LEN 16
1292
1293 #define HMAC_MD5_AlgName (*(const domainname*) "\010" "hmac-md5" "\007" "sig-alg" "\003" "reg" "\003" "int")
1294
1295 // Adapted from Appendix, RFC 2104
1296 mDNSlocal void DNSDigest_ConstructHMACKey(DomainAuthInfo *info, const mDNSu8 *key, mDNSu32 len)
1297 {
1298 MD5_CTX k;
1299 mDNSu8 buf[MD5_LEN];
1300 int i;
1301
1302 // If key is longer than HMAC_LEN reset it to MD5(key)
1303 if (len > HMAC_LEN)
1304 {
1305 MD5_Init(&k);
1306 MD5_Update(&k, key, len);
1307 MD5_Final(buf, &k);
1308 key = buf;
1309 len = MD5_LEN;
1310 }
1311
1312 // store key in pads
1313 mDNSPlatformMemZero(info->keydata_ipad, HMAC_LEN);
1314 mDNSPlatformMemZero(info->keydata_opad, HMAC_LEN);
1315 mDNSPlatformMemCopy(info->keydata_ipad, key, len);
1316 mDNSPlatformMemCopy(info->keydata_opad, key, len);
1317
1318 // XOR key with ipad and opad values
1319 for (i = 0; i < HMAC_LEN; i++)
1320 {
1321 info->keydata_ipad[i] ^= HMAC_IPAD;
1322 info->keydata_opad[i] ^= HMAC_OPAD;
1323 }
1324
1325 }
1326
1327 mDNSexport mDNSs32 DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo *info, const char *b64key)
1328 {
1329 mDNSu8 keybuf[1024];
1330 mDNSs32 keylen = DNSDigest_Base64ToBin(b64key, keybuf, sizeof(keybuf));
1331 if (keylen < 0) return(keylen);
1332 DNSDigest_ConstructHMACKey(info, keybuf, (mDNSu32)keylen);
1333 return(keylen);
1334 }
1335
1336 mDNSexport void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode)
1337 {
1338 AuthRecord tsig;
1339 mDNSu8 *rdata, *const countPtr = (mDNSu8 *)&msg->h.numAdditionals; // Get existing numAdditionals value
1340 mDNSu32 utc32;
1341 mDNSu8 utc48[6];
1342 mDNSu8 digest[MD5_LEN];
1343 mDNSu8 *ptr = *end;
1344 mDNSu32 len;
1345 mDNSOpaque16 buf;
1346 MD5_CTX c;
1347 mDNSu16 numAdditionals = (mDNSu16)((mDNSu16)countPtr[0] << 8 | countPtr[1]);
1348
1349 // Init MD5 context, digest inner key pad and message
1350 MD5_Init(&c);
1351 MD5_Update(&c, info->keydata_ipad, HMAC_LEN);
1352 MD5_Update(&c, (mDNSu8 *)msg, (unsigned long)(*end - (mDNSu8 *)msg));
1353
1354 // Construct TSIG RR, digesting variables as apporpriate
1355 mDNS_SetupResourceRecord(&tsig, mDNSNULL, 0, kDNSType_TSIG, 0, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
1356
1357 // key name
1358 AssignDomainName(&tsig.namestorage, &info->keyname);
1359 MD5_Update(&c, info->keyname.c, DomainNameLength(&info->keyname));
1360
1361 // class
1362 tsig.resrec.rrclass = kDNSQClass_ANY;
1363 buf = mDNSOpaque16fromIntVal(kDNSQClass_ANY);
1364 MD5_Update(&c, buf.b, sizeof(mDNSOpaque16));
1365
1366 // ttl
1367 tsig.resrec.rroriginalttl = 0;
1368 MD5_Update(&c, (mDNSu8 *)&tsig.resrec.rroriginalttl, sizeof(tsig.resrec.rroriginalttl));
1369
1370 // alg name
1371 AssignDomainName(&tsig.resrec.rdata->u.name, &HMAC_MD5_AlgName);
1372 len = DomainNameLength(&HMAC_MD5_AlgName);
1373 rdata = tsig.resrec.rdata->u.data + len;
1374 MD5_Update(&c, HMAC_MD5_AlgName.c, len);
1375
1376 // time
1377 // get UTC (universal time), convert to 48-bit unsigned in network byte order
1378 utc32 = (mDNSu32)mDNSPlatformUTC();
1379 if (utc32 == (unsigned)-1) { LogMsg("ERROR: DNSDigest_SignMessage - mDNSPlatformUTC returned bad time -1"); *end = mDNSNULL; }
1380 utc48[0] = 0;
1381 utc48[1] = 0;
1382 utc48[2] = (mDNSu8)((utc32 >> 24) & 0xff);
1383 utc48[3] = (mDNSu8)((utc32 >> 16) & 0xff);
1384 utc48[4] = (mDNSu8)((utc32 >> 8) & 0xff);
1385 utc48[5] = (mDNSu8)( utc32 & 0xff);
1386
1387 mDNSPlatformMemCopy(rdata, utc48, 6);
1388 rdata += 6;
1389 MD5_Update(&c, utc48, 6);
1390
1391 // 300 sec is fudge recommended in RFC 2485
1392 rdata[0] = (mDNSu8)((300 >> 8) & 0xff);
1393 rdata[1] = (mDNSu8)( 300 & 0xff);
1394 MD5_Update(&c, rdata, sizeof(mDNSOpaque16));
1395 rdata += sizeof(mDNSOpaque16);
1396
1397 // digest error (tcode) and other data len (zero) - we'll add them to the rdata later
1398 buf.b[0] = (mDNSu8)((tcode >> 8) & 0xff);
1399 buf.b[1] = (mDNSu8)( tcode & 0xff);
1400 MD5_Update(&c, buf.b, sizeof(mDNSOpaque16)); // error
1401 buf.NotAnInteger = 0;
1402 MD5_Update(&c, buf.b, sizeof(mDNSOpaque16)); // other data len
1403
1404 // finish the message & tsig var hash
1405 MD5_Final(digest, &c);
1406
1407 // perform outer MD5 (outer key pad, inner digest)
1408 MD5_Init(&c);
1409 MD5_Update(&c, info->keydata_opad, HMAC_LEN);
1410 MD5_Update(&c, digest, MD5_LEN);
1411 MD5_Final(digest, &c);
1412
1413 // set remaining rdata fields
1414 rdata[0] = (mDNSu8)((MD5_LEN >> 8) & 0xff);
1415 rdata[1] = (mDNSu8)( MD5_LEN & 0xff);
1416 rdata += sizeof(mDNSOpaque16);
1417 mDNSPlatformMemCopy(rdata, digest, MD5_LEN); // MAC
1418 rdata += MD5_LEN;
1419 rdata[0] = msg->h.id.b[0]; // original ID
1420 rdata[1] = msg->h.id.b[1];
1421 rdata[2] = (mDNSu8)((tcode >> 8) & 0xff);
1422 rdata[3] = (mDNSu8)( tcode & 0xff);
1423 rdata[4] = 0; // other data len
1424 rdata[5] = 0;
1425 rdata += 6;
1426
1427 tsig.resrec.rdlength = (mDNSu16)(rdata - tsig.resrec.rdata->u.data);
1428 *end = PutResourceRecordTTLJumbo(msg, ptr, &numAdditionals, &tsig.resrec, 0);
1429 if (!*end) { LogMsg("ERROR: DNSDigest_SignMessage - could not put TSIG"); *end = mDNSNULL; return; }
1430
1431 // Write back updated numAdditionals value
1432 countPtr[0] = (mDNSu8)(numAdditionals >> 8);
1433 countPtr[1] = (mDNSu8)(numAdditionals & 0xFF);
1434 }
1435
1436 mDNSexport mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord * lcr, DomainAuthInfo *info, mDNSu16 * rcode, mDNSu16 * tcode)
1437 {
1438 mDNSu8 * ptr = (mDNSu8*) &lcr->r.resrec.rdata->u.data;
1439 mDNSs32 now;
1440 mDNSs32 then;
1441 mDNSu8 thisDigest[MD5_LEN];
1442 mDNSu8 thatDigest[MD5_LEN];
1443 mDNSu32 macsize;
1444 mDNSOpaque16 buf;
1445 mDNSu8 utc48[6];
1446 mDNSs32 delta;
1447 mDNSu16 fudge;
1448 domainname * algo;
1449 MD5_CTX c;
1450 mDNSBool ok = mDNSfalse;
1451
1452 // We only support HMAC-MD5 for now
1453
1454 algo = (domainname*) ptr;
1455
1456 if (!SameDomainName(algo, &HMAC_MD5_AlgName))
1457 {
1458 LogMsg("ERROR: DNSDigest_VerifyMessage - TSIG algorithm not supported: %##s", algo->c);
1459 *rcode = kDNSFlag1_RC_NotAuth;
1460 *tcode = TSIG_ErrBadKey;
1461 ok = mDNSfalse;
1462 goto exit;
1463 }
1464
1465 ptr += DomainNameLength(algo);
1466
1467 // Check the times
1468
1469 now = mDNSPlatformUTC();
1470 if (now == -1)
1471 {
1472 LogMsg("ERROR: DNSDigest_VerifyMessage - mDNSPlatformUTC returned bad time -1");
1473 *rcode = kDNSFlag1_RC_NotAuth;
1474 *tcode = TSIG_ErrBadTime;
1475 ok = mDNSfalse;
1476 goto exit;
1477 }
1478
1479 // Get the 48 bit time field, skipping over the first word
1480
1481 utc48[0] = *ptr++;
1482 utc48[1] = *ptr++;
1483 utc48[2] = *ptr++;
1484 utc48[3] = *ptr++;
1485 utc48[4] = *ptr++;
1486 utc48[5] = *ptr++;
1487
1488 then = (mDNSs32)NToH32(utc48 + sizeof(mDNSu16));
1489
1490 fudge = NToH16(ptr);
1491
1492 ptr += sizeof(mDNSu16);
1493
1494 delta = (now > then) ? now - then : then - now;
1495
1496 if (delta > fudge)
1497 {
1498 LogMsg("ERROR: DNSDigest_VerifyMessage - time skew > %d", fudge);
1499 *rcode = kDNSFlag1_RC_NotAuth;
1500 *tcode = TSIG_ErrBadTime;
1501 ok = mDNSfalse;
1502 goto exit;
1503 }
1504
1505 // MAC size
1506
1507 macsize = (mDNSu32) NToH16(ptr);
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