1 /*
2 **  RSA Data Security, Inc. MD5 Message-Digest Algorithm
3 **
4 **  The standard MD5 message digest routines, from RSA Data Security, Inc.
5 **  by way of Landon Curt Noll, modified and integrated into INN by Clayton
6 **  O'Neill and then simplified somewhat, converted to INN coding style,
7 **  and commented by Russ Allbery.
8 **
9 **  To form the message digest for a message M:
10 **    (1) Initialize a context buffer md5_context using md5_init
11 **    (2) Call md5_update on md5_context and M
12 **    (3) Call md5_final on md5_context
13 **  The message digest is now in md5_context->digest[0...15].
14 **
15 **  Alternately, just call md5_hash on M, passing it a buffer of at least
16 **  16 bytes into which to put the digest.  md5_hash does the above
17 **  internally for you and is the most convenient interface; the interface
18 **  described above, however, is better when all of the data to hash isn't
19 **  available neatly in a single buffer (such as hashing data aquired a
20 **  block at a time).
21 **
22 **  For information about MD5, see RFC 1321.
23 **
24 **  LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
25 **  INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO
26 **  EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
27 **  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
28 **  USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
29 **  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
30 **  PERFORMANCE OF THIS SOFTWARE.
31 **
32 **  Copyright (C) 1990, RSA Data Security, Inc.  All rights reserved.
33 **
34 **  License to copy and use this software is granted provided that it is
35 **  identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm"
36 **  in all material mentioning or referencing this software or this
37 **  function.
38 **
39 **  License is also granted to make and use derivative works provided that
40 **  such works are identified as "derived from the RSA Data Security,
41 **  Inc. MD5 Message-Digest Algorithm" in all material mentioning or
42 **  referencing the derived work.
43 **
44 **  RSA Data Security, Inc. makes no representations concerning either the
45 **  merchantability of this software or the suitability of this software for
46 **  any particular purpose.  It is provided "as is" without express or
47 **  implied warranty of any kind.
48 **
49 **  These notices must be retained in any copies of any part of this
50 **  documentation and/or software.
51 */
52 
53 /*
54 **  The actual mathematics and cryptography are at the bottom of this file,
55 **  as those parts should be fully debugged and very infrequently changed.
56 **  The core of actual work is done by md5_transform.  The beginning of this
57 **  file contains the infrastructure around the mathematics.
58 */
59 
60 #include "portable/system.h"
61 
62 #include "inn/md5.h"
63 
64 /* Rotate a 32-bit value left, used by both the MD5 mathematics and by the
65    routine below to byteswap data on big-endian machines. */
66 #define ROT(X, n) (((X) << (n)) | ((X) >> (32 - (n))))
67 
68 /* Almost zero fill padding, used by md5_final.  The 0x80 is part of the MD5
69    hash algorithm, from RFC 1321 section 3.1:
70 
71      Padding is performed as follows: a single "1" bit is appended to the
72      message, and then "0" bits are appended so that the length in bits of
73      the padded message becomes congruent to 448, modulo 512.  In all, at
74      least one bit and at most 512 bits are appended.
75 
76    Let the compiler zero the remainder of the array for us, guaranteed by
77    ISO C99 6.7.8 paragraph 21. */
78 static const unsigned char padding[MD5_CHUNKSIZE] = {0x80, 0 /* 0, ... */};
79 
80 /* Internal prototypes. */
81 static void md5_transform(uint32_t *, const uint32_t *);
82 static void md5_update_block(struct md5_context *, const unsigned char *,
83                              size_t);
84 
85 /* MD5 requires that input data be treated as words in little-endian byte
86    order.  From RFC 1321 section 2:
87 
88      Similarly, a sequence of bytes can be interpreted as a sequence of
89      32-bit words, where each consecutive group of four bytes is interpreted
90      as a word with the low-order (least significant) byte given first.
91 
92    Input data must therefore be byteswapped on big-endian machines, as must
93    the 16-byte result digest.  Since we have to make a copy of the incoming
94    data anyway to ensure alignment for 4-byte access, we can byteswap it in
95    place. */
96 #if !WORDS_BIGENDIAN
97 #    define decode(data)      /* empty */
98 #    define encode(data, out) memcpy((out), (data), MD5_DIGESTSIZE)
99 #else
100 
101 /* The obvious way to do this is to pull single bytes at a time out of the
102    input array and build words from them; this requires three shifts and
103    three Boolean or operations, but it requires four memory reads per word
104    unless the compiler is really smart.  Since we can assume four-byte
105    alignment for the input data, use this optimized routine from J. Touch,
106    USC/ISI.  This requires four shifts, two ands, and two ors, but only one
107    memory read per word. */
108 #    define swap(word)              \
109         do {                        \
110             htmp = ROT((word), 16); \
111             ltmp = htmp >> 8;       \
112             htmp &= 0x00ff00ff;     \
113             ltmp &= 0x00ff00ff;     \
114             htmp <<= 8;             \
115             (word) = htmp | ltmp;   \
116         } while (0)
117 
118 /* We process 16 words of data (one MD5 block) of data at a time, completely
119    unrolling the loop manually since it should allow the compiler to take
120    advantage of pipelining and parallel arithmetic units. */
121 static void
decode(uint32_t * data)122 decode(uint32_t *data)
123 {
124     uint32_t ltmp, htmp;
125 
126     swap(data[0]);
127     swap(data[1]);
128     swap(data[2]);
129     swap(data[3]);
130     swap(data[4]);
131     swap(data[5]);
132     swap(data[6]);
133     swap(data[7]);
134     swap(data[8]);
135     swap(data[9]);
136     swap(data[10]);
137     swap(data[11]);
138     swap(data[12]);
139     swap(data[13]);
140     swap(data[14]);
141     swap(data[15]);
142 }
143 
144 /* Used by md5_final to generate the final digest.  The digest is not
145    guaranteed to be aligned for 4-byte access but we are allowed to be
146    destructive, so byteswap first and then copy the result over. */
147 static void
encode(uint32_t * data,unsigned char * out)148 encode(uint32_t *data, unsigned char *out)
149 {
150     uint32_t ltmp, htmp;
151 
152     swap(data[0]);
153     swap(data[1]);
154     swap(data[2]);
155     swap(data[3]);
156     memcpy(out, data, MD5_DIGESTSIZE);
157 }
158 
159 #endif /* WORDS_BIGENDIAN */
160 
161 
162 /*
163 **  That takes care of the preliminaries; now the real fun begins.  The
164 **  initialization function for a struct md5_context; set lengths to zero
165 **  and initialize our working buffer with the magic constants (c.f. RFC
166 **  1321 section 3.3).
167 */
168 void
md5_init(struct md5_context * context)169 md5_init(struct md5_context *context)
170 {
171     context->buf[0] = 0x67452301U;
172     context->buf[1] = 0xefcdab89U;
173     context->buf[2] = 0x98badcfeU;
174     context->buf[3] = 0x10325476U;
175 
176     context->count[0] = 0;
177     context->count[1] = 0;
178     context->datalen = 0;
179 }
180 
181 
182 /*
183 **  The workhorse function, called for each chunk of data.  Update the
184 **  message-digest context to account for the presence of each of the
185 **  characters data[0 .. count - 1] in the message whose digest is being
186 **  computed.  Accepts any length of data; all whole blocks are processed
187 **  and the remaining data is buffered for later processing by either
188 **  another call to md5_update or by md5_final.
189 */
190 void
md5_update(struct md5_context * context,const unsigned char * data,size_t count)191 md5_update(struct md5_context *context, const unsigned char *data,
192            size_t count)
193 {
194     unsigned int datalen = context->datalen;
195     unsigned int left;
196     size_t high_count, low_count, used;
197 
198     /* Update the count of hashed bytes.  The machinations here are to do
199        the right thing on a platform where size_t > 32 bits without causing
200        compiler warnings on platforms where it's 32 bits.  RFC 1321 section
201        3.2 says:
202 
203          A 64-bit representation of b (the length of the message before the
204          padding bits were added) is appended to the result of the previous
205          step.  In the unlikely event that b is greater than 2^64, then only
206          the low-order 64 bits of b are used.
207 
208        so we can just ignore the higher bits of count if size_t is larger
209        than 64 bits.  (Think ahead!)  If size_t is only 32 bits, the
210        compiler should kill the whole if statement as dead code. */
211     if (sizeof(count) > 4) {
212         high_count = count >> 31;
213         context->count[1] += (high_count >> 1) & 0xffffffffU;
214     }
215 
216     /* Now deal with count[0].  Add in the low 32 bits of count and
217        increment count[1] if count[0] wraps.  Isn't unsigned arithmetic
218        cool? */
219     low_count = count & 0xffffffffU;
220     context->count[0] += low_count;
221     if (context->count[0] < low_count)
222         context->count[1]++;
223 
224     /* See if we already have some data queued.  If so, try to complete a
225        block and then deal with it first.  If the new data still doesn't
226        fill the buffer, add it to the buffer and return.  Otherwise,
227        transform that block and update data and count to account for the
228        data we've already used. */
229     if (datalen > 0) {
230         left = MD5_CHUNKSIZE - datalen;
231         if (left > count) {
232             memcpy(context->in.byte + datalen, data, count);
233             context->datalen += count;
234             return;
235         } else {
236             memcpy(context->in.byte + datalen, data, left);
237             decode(context->in.word);
238             md5_transform(context->buf, context->in.word);
239             data += left;
240             count -= left;
241             context->datalen = 0;
242         }
243     }
244 
245     /* If we have a block of data or more left, pass the rest off to
246        md5_update_block to deal with all of the full blocks available. */
247     if (count >= MD5_CHUNKSIZE) {
248         md5_update_block(context, data, count);
249         used = (count / MD5_CHUNKSIZE) * MD5_CHUNKSIZE;
250         data += used;
251         count -= used;
252     }
253 
254     /* If there's anything left, buffer it until we can complete a block or
255        for md5_final to deal with. */
256     if (count > 0) {
257         memcpy(context->in.byte, data, count);
258         context->datalen = count;
259     }
260 }
261 
262 
263 /*
264 **  Update the message-digest context to account for the presence of each of
265 **  the characters data[0 .. count - 1] in the message whose digest is being
266 **  computed, except that we only deal with full blocks of data.  The data
267 **  is processed one block at a time, and partial blocks at the end are
268 **  ignored (they're dealt with by md5_update, which calls this routine.
269 **
270 **  Note that we always make a copy of the input data into an array of
271 **  4-byte values.  If our input data were guaranteed to be aligned for
272 **  4-byte access, we could just use the input buffer directly on
273 **  little-endian machines, and in fact this implementation used to do that.
274 **  However, a requirement to align isn't always easily detectable, even by
275 **  configure (an Alpha running Tru64 will appear to allow unaligned
276 **  accesses, but will spew errors to the terminal if you do it).  On top of
277 **  that, even when it's allowed, unaligned access is quite frequently
278 **  slower; we're about to do four reads of each word of the input data for
279 **  the calculations, so doing one additional copy of the data up-front is
280 **  probably worth it.
281 */
282 static void
md5_update_block(struct md5_context * context,const unsigned char * data,size_t count)283 md5_update_block(struct md5_context *context, const unsigned char *data,
284                  size_t count)
285 {
286     uint32_t in[MD5_CHUNKWORDS];
287 
288     /* Process data in MD5_CHUNKSIZE blocks. */
289     while (count >= MD5_CHUNKSIZE) {
290         memcpy(in, data, MD5_CHUNKSIZE);
291         decode(in);
292         md5_transform(context->buf, in);
293         data += MD5_CHUNKSIZE;
294         count -= MD5_CHUNKSIZE;
295     }
296 }
297 
298 
299 /*
300 **  Terminates the message-digest computation, accounting for any final
301 **  trailing data and adding the message length to the hashed data, and ends
302 **  with the desired message digest in context->digest[0...15].
303 */
304 void
md5_final(struct md5_context * context)305 md5_final(struct md5_context *context)
306 {
307     unsigned int pad_needed, left;
308     uint32_t count[2];
309     uint32_t *countloc;
310 
311     /* Save the count before appending the padding. */
312     count[0] = context->count[0];
313     count[1] = context->count[1];
314 
315     /* Pad the final block of data.  RFC 1321 section 3.1:
316 
317          The message is "padded" (extended) so that its length (in bits) is
318          congruent to 448, modulo 512.  That is, the message is extended so
319          that it is just 64 bits shy of being a multiple of 512 bits long.
320          Padding is always performed, even if the length of the message is
321          already congruent to 448, modulo 512.
322 
323        The 64 bits (two words) left are for the 64-bit count of bits
324        hashed.  We'll need at most 64 bytes of padding; lucky that the
325        padding array is exactly that size! */
326     left = context->datalen;
327     pad_needed = (left < 64 - 8) ? (64 - 8 - left) : (128 - 8 - left);
328     md5_update(context, padding, pad_needed);
329 
330     /* Append length in bits and transform.  Note that we cheat slightly
331        here to save a few operations on big-endian machines; the algorithm
332        says that we should add the length, in little-endian byte order, to
333        the last block of data.  We'd then transform it into big-endian order
334        on a big-endian machine.  But the count is *already* in big-endian
335        order on a big-endian machine, so effectively we'd be byteswapping it
336        twice.  Instead, add it to the block after doing byte swapping on the
337        rest.
338 
339        Note that we've been counting *bytes*, but the algorithm demands the
340        length in *bits*, so shift things around a bit. */
341     decode(context->in.word);
342     countloc = &context->in.word[MD5_CHUNKWORDS - 2];
343     countloc[0] = count[0] << 3;
344     countloc[1] = (count[1] << 3) | (count[0] >> 29);
345     md5_transform(context->buf, context->in.word);
346 
347     /* Recover the final digest.  Whoo-hoo, we're done! */
348     encode(context->buf, context->digest);
349 }
350 
351 
352 /*
353 **  A convenience wrapper around md5_init, md5_update, and md5_final.  Takes
354 **  a pointer to a buffer of data, the length of the data, and a pointer to
355 **  a buffer of at least 16 bytes into which to write the message digest.
356 */
357 void
md5_hash(const unsigned char * data,size_t length,unsigned char * digest)358 md5_hash(const unsigned char *data, size_t length, unsigned char *digest)
359 {
360     struct md5_context context;
361 
362     md5_init(&context);
363     md5_update(&context, data, length);
364     md5_final(&context);
365     memcpy(digest, context.digest, MD5_DIGESTSIZE);
366 }
367 
368 
369 /*
370 **  Look out, here comes the math.
371 **
372 **  There are no user-serviceable parts below this point unless you know
373 **  quite a bit about MD5 or optimization of integer math.  The only
374 **  function remaining, down below, is md5_transform; the rest of this is
375 **  setting up macros to make that function more readable.
376 **
377 **  The F, G, H and I are basic MD5 functions.  The following identity saves
378 **  one boolean operation.
379 **
380 **  F: (((x) & (y)) | (~(x) & (z))) == ((z) ^ ((x) & ((y) ^ (z))))
381 **  G: (((x) & (z)) | ((y) & ~(z))) == ((y) ^ ((z) & ((x) ^ (y))))
382 */
383 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
384 #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
385 #define H(x, y, z) ((x) ^ (y) ^ (z))
386 #define I(x, y, z) ((y) ^ ((x) | (~z)))
387 
388 /*
389 **  FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.  Rotation
390 **  is separate from addition to prevent recomputation.  S?? are the shift
391 **  values for each round.
392 */
393 #define S11 7
394 #define S12 12
395 #define S13 17
396 #define S14 22
397 #define FF(a, b, c, d, x, s, ac)                        \
398     {                                                   \
399         (a) += F((b), (c), (d)) + (x) + (uint32_t)(ac); \
400         (a) = ROT((a), (s));                            \
401         (a) += (b);                                     \
402     }
403 
404 #define S21 5
405 #define S22 9
406 #define S23 14
407 #define S24 20
408 #define GG(a, b, c, d, x, s, ac)                        \
409     {                                                   \
410         (a) += G((b), (c), (d)) + (x) + (uint32_t)(ac); \
411         (a) = ROT((a), (s));                            \
412         (a) += (b);                                     \
413     }
414 
415 #define S31 4
416 #define S32 11
417 #define S33 16
418 #define S34 23
419 #define HH(a, b, c, d, x, s, ac)                        \
420     {                                                   \
421         (a) += H((b), (c), (d)) + (x) + (uint32_t)(ac); \
422         (a) = ROT((a), (s));                            \
423         (a) += (b);                                     \
424     }
425 
426 #define S41 6
427 #define S42 10
428 #define S43 15
429 #define S44 21
430 #define II(a, b, c, d, x, s, ac)                        \
431     {                                                   \
432         (a) += I((b), (c), (d)) + (x) + (uint32_t)(ac); \
433         (a) = ROT((a), (s));                            \
434         (a) += (b);                                     \
435     }
436 
437 /*
438 **  Basic MD5 step.  Transforms buf based on in.
439 */
440 static void
md5_transform(uint32_t * buf,const uint32_t * in)441 md5_transform(uint32_t *buf, const uint32_t *in)
442 {
443     uint32_t a = buf[0];
444     uint32_t b = buf[1];
445     uint32_t c = buf[2];
446     uint32_t d = buf[3];
447 
448     /* clang-format off */
449     /* Round 1 */
450     FF(a, b, c, d, in[ 0], S11, 3614090360UL); /*  1 */
451     FF(d, a, b, c, in[ 1], S12, 3905402710UL); /*  2 */
452     FF(c, d, a, b, in[ 2], S13,  606105819UL); /*  3 */
453     FF(b, c, d, a, in[ 3], S14, 3250441966UL); /*  4 */
454     FF(a, b, c, d, in[ 4], S11, 4118548399UL); /*  5 */
455     FF(d, a, b, c, in[ 5], S12, 1200080426UL); /*  6 */
456     FF(c, d, a, b, in[ 6], S13, 2821735955UL); /*  7 */
457     FF(b, c, d, a, in[ 7], S14, 4249261313UL); /*  8 */
458     FF(a, b, c, d, in[ 8], S11, 1770035416UL); /*  9 */
459     FF(d, a, b, c, in[ 9], S12, 2336552879UL); /* 10 */
460     FF(c, d, a, b, in[10], S13, 4294925233UL); /* 11 */
461     FF(b, c, d, a, in[11], S14, 2304563134UL); /* 12 */
462     FF(a, b, c, d, in[12], S11, 1804603682UL); /* 13 */
463     FF(d, a, b, c, in[13], S12, 4254626195UL); /* 14 */
464     FF(c, d, a, b, in[14], S13, 2792965006UL); /* 15 */
465     FF(b, c, d, a, in[15], S14, 1236535329UL); /* 16 */
466 
467     /* Round 2 */
468     GG(a, b, c, d, in[ 1], S21, 4129170786UL); /* 17 */
469     GG(d, a, b, c, in[ 6], S22, 3225465664UL); /* 18 */
470     GG(c, d, a, b, in[11], S23,  643717713UL); /* 19 */
471     GG(b, c, d, a, in[ 0], S24, 3921069994UL); /* 20 */
472     GG(a, b, c, d, in[ 5], S21, 3593408605UL); /* 21 */
473     GG(d, a, b, c, in[10], S22,   38016083UL); /* 22 */
474     GG(c, d, a, b, in[15], S23, 3634488961UL); /* 23 */
475     GG(b, c, d, a, in[ 4], S24, 3889429448UL); /* 24 */
476     GG(a, b, c, d, in[ 9], S21,  568446438UL); /* 25 */
477     GG(d, a, b, c, in[14], S22, 3275163606UL); /* 26 */
478     GG(c, d, a, b, in[ 3], S23, 4107603335UL); /* 27 */
479     GG(b, c, d, a, in[ 8], S24, 1163531501UL); /* 28 */
480     GG(a, b, c, d, in[13], S21, 2850285829UL); /* 29 */
481     GG(d, a, b, c, in[ 2], S22, 4243563512UL); /* 30 */
482     GG(c, d, a, b, in[ 7], S23, 1735328473UL); /* 31 */
483     GG(b, c, d, a, in[12], S24, 2368359562UL); /* 32 */
484 
485     /* Round 3 */
486     HH(a, b, c, d, in[ 5], S31, 4294588738UL); /* 33 */
487     HH(d, a, b, c, in[ 8], S32, 2272392833UL); /* 34 */
488     HH(c, d, a, b, in[11], S33, 1839030562UL); /* 35 */
489     HH(b, c, d, a, in[14], S34, 4259657740UL); /* 36 */
490     HH(a, b, c, d, in[ 1], S31, 2763975236UL); /* 37 */
491     HH(d, a, b, c, in[ 4], S32, 1272893353UL); /* 38 */
492     HH(c, d, a, b, in[ 7], S33, 4139469664UL); /* 39 */
493     HH(b, c, d, a, in[10], S34, 3200236656UL); /* 40 */
494     HH(a, b, c, d, in[13], S31,  681279174UL); /* 41 */
495     HH(d, a, b, c, in[ 0], S32, 3936430074UL); /* 42 */
496     HH(c, d, a, b, in[ 3], S33, 3572445317UL); /* 43 */
497     HH(b, c, d, a, in[ 6], S34,   76029189UL); /* 44 */
498     HH(a, b, c, d, in[ 9], S31, 3654602809UL); /* 45 */
499     HH(d, a, b, c, in[12], S32, 3873151461UL); /* 46 */
500     HH(c, d, a, b, in[15], S33,  530742520UL); /* 47 */
501     HH(b, c, d, a, in[ 2], S34, 3299628645UL); /* 48 */
502 
503     /* Round 4 */
504     II(a, b, c, d, in[ 0], S41, 4096336452UL); /* 49 */
505     II(d, a, b, c, in[ 7], S42, 1126891415UL); /* 50 */
506     II(c, d, a, b, in[14], S43, 2878612391UL); /* 51 */
507     II(b, c, d, a, in[ 5], S44, 4237533241UL); /* 52 */
508     II(a, b, c, d, in[12], S41, 1700485571UL); /* 53 */
509     II(d, a, b, c, in[ 3], S42, 2399980690UL); /* 54 */
510     II(c, d, a, b, in[10], S43, 4293915773UL); /* 55 */
511     II(b, c, d, a, in[ 1], S44, 2240044497UL); /* 56 */
512     II(a, b, c, d, in[ 8], S41, 1873313359UL); /* 57 */
513     II(d, a, b, c, in[15], S42, 4264355552UL); /* 58 */
514     II(c, d, a, b, in[ 6], S43, 2734768916UL); /* 59 */
515     II(b, c, d, a, in[13], S44, 1309151649UL); /* 60 */
516     II(a, b, c, d, in[ 4], S41, 4149444226UL); /* 61 */
517     II(d, a, b, c, in[11], S42, 3174756917UL); /* 62 */
518     II(c, d, a, b, in[ 2], S43,  718787259UL); /* 63 */
519     II(b, c, d, a, in[ 9], S44, 3951481745UL); /* 64 */
520     /* clang-format on */
521 
522     buf[0] += a;
523     buf[1] += b;
524     buf[2] += c;
525     buf[3] += d;
526 }
527