1 /*
2 ** The code is modified for use in fossil.  The original header
3 ** comment follows:
4 */
5 /*
6  * This code implements the MD5 message-digest algorithm.
7  * The algorithm is due to Ron Rivest.  This code was
8  * written by Colin Plumb in 1993, no copyright is claimed.
9  * This code is in the public domain; do with it what you wish.
10  *
11  * Equivalent code is available from RSA Data Security, Inc.
12  * This code has been tested against that, and is equivalent,
13  * except that you don't need to include two pages of legalese
14  * with every copy.
15  *
16  * To compute the message digest of a chunk of bytes, declare an
17  * MD5Context structure, pass it to MD5Init, call MD5Update as
18  * needed on buffers full of bytes, and then call MD5Final, which
19  * will fill a supplied 16-byte array with the digest.
20  */
21 #include "config.h"
22 #include <string.h>
23 #include <stdio.h>
24 #include <sqlite3.h>
25 #include "md5.h"
26 
27 #ifdef FOSSIL_ENABLE_SSL
28 
29 # include <openssl/md5.h>
30 # define MD5Context MD5_CTX
31 # define MD5Init MD5_Init
32 # define MD5Update MD5_Update
33 # define MD5Final MD5_Final
34 
35 #else
36 
37 /*
38  * If compiled on a machine that doesn't have a 32-bit integer,
39  * you just set "uint32" to the appropriate datatype for an
40  * unsigned 32-bit integer.  For example:
41  *
42  *       cc -Duint32='unsigned long' md5.c
43  *
44  */
45 #ifndef uint32
46 #  define uint32 unsigned int
47 #endif
48 
49 struct Context {
50   int isInit;
51   uint32 buf[4];
52   uint32 bits[2];
53   unsigned char in[64];
54 };
55 typedef struct Context MD5Context;
56 
57 #if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
58     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
59     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
60     defined(__arm__)  || defined(_WIN32)
61 # define byteReverse(A,B)
62 #else
63 /*
64  * Convert an array of integers to little-endian.
65  * Note: this code is a no-op on little-endian machines.
66  */
byteReverse(unsigned char * buf,unsigned longs)67 static void byteReverse (unsigned char *buf, unsigned longs){
68         uint32 t;
69         do {
70                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
71                             ((unsigned)buf[1]<<8 | buf[0]);
72                 *(uint32 *)buf = t;
73                 buf += 4;
74         } while (--longs);
75 }
76 #endif
77 
78 /* The four core functions - F1 is optimized somewhat */
79 
80 /* #define F1(x, y, z) (x & y | ~x & z) */
81 #define F1(x, y, z) (z ^ (x & (y ^ z)))
82 #define F2(x, y, z) F1(z, x, y)
83 #define F3(x, y, z) (x ^ y ^ z)
84 #define F4(x, y, z) (y ^ (x | ~z))
85 
86 /* This is the central step in the MD5 algorithm. */
87 #define MD5STEP(f, w, x, y, z, data, s) \
88         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
89 
90 /*
91  * The core of the MD5 algorithm, this alters an existing MD5 hash to
92  * reflect the addition of 16 longwords of new data.  MD5Update blocks
93  * the data and converts bytes into longwords for this routine.
94  */
MD5Transform(uint32 buf[4],const uint32 in[16])95 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
96         register uint32 a, b, c, d;
97 
98         a = buf[0];
99         b = buf[1];
100         c = buf[2];
101         d = buf[3];
102 
103         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
104         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
105         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
106         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
107         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
108         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
109         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
110         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
111         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
112         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
113         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
114         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
115         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
116         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
117         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
118         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
119 
120         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
121         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
122         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
123         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
124         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
125         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
126         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
127         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
128         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
129         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
130         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
131         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
132         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
133         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
134         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
135         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
136 
137         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
138         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
139         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
140         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
141         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
142         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
143         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
144         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
145         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
146         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
147         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
148         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
149         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
150         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
151         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
152         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
153 
154         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
155         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
156         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
157         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
158         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
159         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
160         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
161         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
162         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
163         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
164         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
165         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
166         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
167         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
168         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
169         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
170 
171         buf[0] += a;
172         buf[1] += b;
173         buf[2] += c;
174         buf[3] += d;
175 }
176 
177 /*
178  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
179  * initialization constants.
180  */
MD5Init(MD5Context * ctx)181 static void MD5Init(MD5Context *ctx){
182         ctx->isInit = 1;
183         ctx->buf[0] = 0x67452301;
184         ctx->buf[1] = 0xefcdab89;
185         ctx->buf[2] = 0x98badcfe;
186         ctx->buf[3] = 0x10325476;
187         ctx->bits[0] = 0;
188         ctx->bits[1] = 0;
189 }
190 
191 /*
192  * Update context to reflect the concatenation of another buffer full
193  * of bytes.
194  */
195 static
MD5Update(MD5Context * pCtx,const unsigned char * buf,unsigned int len)196 void MD5Update(MD5Context *pCtx, const unsigned char *buf, unsigned int len){
197         struct Context *ctx = (struct Context *)pCtx;
198         uint32 t;
199 
200         /* Update bitcount */
201 
202         t = ctx->bits[0];
203         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
204                 ctx->bits[1]++; /* Carry from low to high */
205         ctx->bits[1] += len >> 29;
206 
207         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
208 
209         /* Handle any leading odd-sized chunks */
210 
211         if ( t ) {
212                 unsigned char *p = (unsigned char *)ctx->in + t;
213 
214                 t = 64-t;
215                 if (len < t) {
216                         memcpy(p, buf, len);
217                         return;
218                 }
219                 memcpy(p, buf, t);
220                 byteReverse(ctx->in, 16);
221                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
222                 buf += t;
223                 len -= t;
224         }
225 
226         /* Process data in 64-byte chunks */
227 
228         while (len >= 64) {
229                 memcpy(ctx->in, buf, 64);
230                 byteReverse(ctx->in, 16);
231                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
232                 buf += 64;
233                 len -= 64;
234         }
235 
236         /* Handle any remaining bytes of data. */
237 
238         memcpy(ctx->in, buf, len);
239 }
240 
241 /*
242  * Final wrapup - pad to 64-byte boundary with the bit pattern
243  * 1 0* (64-bit count of bits processed, MSB-first)
244  */
MD5Final(unsigned char digest[16],MD5Context * pCtx)245 static void MD5Final(unsigned char digest[16], MD5Context *pCtx){
246         struct Context *ctx = (struct Context *)pCtx;
247         unsigned count;
248         unsigned char *p;
249 
250         /* Compute number of bytes mod 64 */
251         count = (ctx->bits[0] >> 3) & 0x3F;
252 
253         /* Set the first char of padding to 0x80.  This is safe since there is
254            always at least one byte free */
255         p = ctx->in + count;
256         *p++ = 0x80;
257 
258         /* Bytes of padding needed to make 64 bytes */
259         count = 64 - 1 - count;
260 
261         /* Pad out to 56 mod 64 */
262         if (count < 8) {
263                 /* Two lots of padding:  Pad the first block to 64 bytes */
264                 memset(p, 0, count);
265                 byteReverse(ctx->in, 16);
266                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
267 
268                 /* Now fill the next block with 56 bytes */
269                 memset(ctx->in, 0, 56);
270         } else {
271                 /* Pad block to 56 bytes */
272                 memset(p, 0, count-8);
273         }
274         byteReverse(ctx->in, 14);
275 
276         /* Append length in bits and transform */
277         memcpy(&ctx->in[14*sizeof(uint32)], ctx->bits, 2*sizeof(uint32));
278 
279         MD5Transform(ctx->buf, (uint32 *)ctx->in);
280         byteReverse((unsigned char *)ctx->buf, 4);
281         memcpy(digest, ctx->buf, 16);
282         memset(ctx, 0, sizeof(*ctx));    /* In case it's sensitive */
283 }
284 #endif
285 
286 /*
287 ** Convert a digest into base-16.  digest should be declared as
288 ** "unsigned char digest[16]" in the calling function.  The MD5
289 ** digest is stored in the first 16 bytes.  zBuf should
290 ** be "char zBuf[33]".
291 */
DigestToBase16(unsigned char * digest,char * zBuf)292 static void DigestToBase16(unsigned char *digest, char *zBuf){
293   static const char zEncode[] = "0123456789abcdef";
294   int i, j;
295 
296   for(j=i=0; i<16; i++){
297     int a = digest[i];
298     zBuf[j++] = zEncode[(a>>4)&0xf];
299     zBuf[j++] = zEncode[a & 0xf];
300   }
301   zBuf[j] = 0;
302 }
303 
304 /*
305 ** The state of a incremental MD5 checksum computation.  Only one
306 ** such computation can be underway at a time, of course.
307 */
308 static MD5Context incrCtx;
309 static int incrInit = 0;
310 
311 /*
312 ** Initialize the incremental MD5 checksum.
313 */
md5sum_init(void)314 void md5sum_init(void){
315   incrInit = 0;
316 }
317 
318 /*
319 ** Add more text to the incremental MD5 checksum.
320 */
md5sum_step_text(const char * zText,int nBytes)321 void md5sum_step_text(const char *zText, int nBytes){
322   if( !incrInit ){
323     MD5Init(&incrCtx);
324     incrInit = 1;
325   }
326   if( nBytes<=0 ){
327     if( nBytes==0 ) return;
328     nBytes = strlen(zText);
329   }
330   MD5Update(&incrCtx, (unsigned char*)zText, nBytes);
331 }
332 
333 /*
334 ** Add the content of a blob to the incremental MD5 checksum.
335 */
md5sum_step_blob(Blob * p)336 void md5sum_step_blob(Blob *p){
337   md5sum_step_text(blob_buffer(p), blob_size(p));
338 }
339 
340 /*
341 ** For trouble-shooting only:
342 **
343 ** Report the current state of the incremental checksum.
344 */
md5sum_current_state(void)345 const char *md5sum_current_state(void){
346   unsigned int cksum = 0;
347   unsigned int *pFirst, *pLast;
348   static char zResult[12];
349 
350   pFirst = (unsigned int*)&incrCtx;
351   pLast = (unsigned int*)((&incrCtx)+1);
352   while( pFirst<pLast ){
353     cksum += *pFirst;
354     pFirst++;
355   }
356   sqlite3_snprintf(sizeof(zResult), zResult, "%08x", cksum);
357   return zResult;
358 }
359 
360 /*
361 ** Finish the incremental MD5 checksum.  Store the result in blob pOut
362 ** if pOut!=0.  Also return a pointer to the result.
363 **
364 ** This resets the incremental checksum preparing for the next round
365 ** of computation.  The return pointer points to a static buffer that
366 ** is overwritten by subsequent calls to this function.
367 */
md5sum_finish(Blob * pOut)368 char *md5sum_finish(Blob *pOut){
369   unsigned char zResult[16];
370   static char zOut[33];
371   md5sum_step_text(0,0);
372   MD5Final(zResult, &incrCtx);
373   incrInit = 0;
374   DigestToBase16(zResult, zOut);
375   if( pOut ){
376     blob_zero(pOut);
377     blob_append(pOut, zOut, 32);
378   }
379   return zOut;
380 }
381 
382 
383 /*
384 ** Compute the MD5 checksum of a file on disk.  Store the resulting
385 ** checksum in the blob pCksum.  pCksum is assumed to be initialized.
386 **
387 ** Return the number of errors.
388 */
md5sum_file(const char * zFilename,Blob * pCksum)389 int md5sum_file(const char *zFilename, Blob *pCksum){
390   FILE *in;
391   MD5Context ctx;
392   unsigned char zResult[16];
393   char zBuf[10240];
394 
395   in = fossil_fopen(zFilename,"rb");
396   if( in==0 ){
397     return 1;
398   }
399   MD5Init(&ctx);
400   for(;;){
401     int n;
402     n = fread(zBuf, 1, sizeof(zBuf), in);
403     if( n<=0 ) break;
404     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
405   }
406   fclose(in);
407   blob_zero(pCksum);
408   blob_resize(pCksum, 32);
409   MD5Final(zResult, &ctx);
410   DigestToBase16(zResult, blob_buffer(pCksum));
411   return 0;
412 }
413 
414 /*
415 ** Compute the MD5 checksum of a blob in memory.  Store the resulting
416 ** checksum in the blob pCksum.  pCksum is assumed to be either
417 ** uninitialized or the same blob as pIn.
418 **
419 ** Return the number of errors.
420 */
md5sum_blob(const Blob * pIn,Blob * pCksum)421 int md5sum_blob(const Blob *pIn, Blob *pCksum){
422   MD5Context ctx;
423   unsigned char zResult[16];
424 
425   MD5Init(&ctx);
426   MD5Update(&ctx, (unsigned char*)blob_buffer(pIn), blob_size(pIn));
427   if( pIn==pCksum ){
428     blob_reset(pCksum);
429   }else{
430     blob_zero(pCksum);
431   }
432   blob_resize(pCksum, 32);
433   MD5Final(zResult, &ctx);
434   DigestToBase16(zResult, blob_buffer(pCksum));
435   return 0;
436 }
437 
438 
439 /*
440 ** COMMAND: md5sum*
441 **
442 ** Usage: %fossil md5sum FILES....
443 **
444 ** Compute an MD5 checksum of all files named on the command-line.
445 ** If a file is named "-" then content is read from standard input.
446 */
md5sum_test(void)447 void md5sum_test(void){
448   int i;
449   Blob in;
450   Blob cksum;
451 
452   for(i=2; i<g.argc; i++){
453     blob_init(&cksum, "********** not found ***********", -1);
454     if( g.argv[i][0]=='-' && g.argv[i][1]==0 ){
455       blob_read_from_channel(&in, stdin, -1);
456       md5sum_blob(&in, &cksum);
457     }else{
458       md5sum_file(g.argv[i], &cksum);
459     }
460     fossil_print("%s  %s\n", blob_str(&cksum), g.argv[i]);
461     blob_reset(&cksum);
462   }
463 }
464