Fossil

File Content
Login

Latest version of file '':


     1  /*
     2  ** Copyright (c) 2006 D. Richard Hipp
     3  **
     4  ** This program is free software; you can redistribute it and/or
     5  ** modify it under the terms of the Simplified BSD License (also
     6  ** known as the "2-Clause License" or "FreeBSD License".)
     7  **
     8  ** This program is distributed in the hope that it will be useful,
     9  ** but without any warranty; without even the implied warranty of
    10  ** merchantability or fitness for a particular purpose.
    11  **
    12  ** Author contact information:
    13  **   drh@hwaci.com
    14  **   http://www.hwaci.com/drh/
    15  **
    16  *******************************************************************************
    17  **
    18  ** This implementation of SHA1.
    19  */
    20  #include "config.h"
    21  #include <sys/types.h>
    22  #include "sha1.h"
    23  
    24  
    25  /*
    26  ** SHA1 Implementation #1 is the hardened SHA1 implementation by
    27  ** Marc Stevens.  Code obtained from GitHub
    28  **
    29  **     https://github.com/cr-marcstevens/sha1collisiondetection
    30  **
    31  ** Downloaded on 2017-03-01 then repackaged to work with Fossil
    32  ** and makeheaders.
    33  */
    34  #if FOSSIL_HARDENED_SHA1
    35  
    36  #if INTERFACE
    37  typedef void(*collision_block_callback)(uint64_t, const uint32_t*, const uint32_t*, const uint32_t*, const uint32_t*);
    38  struct SHA1_CTX {
    39    uint64_t total;
    40    uint32_t ihv[5];
    41    unsigned char buffer[64];
    42    int bigendian;
    43    int found_collision;
    44    int safe_hash;
    45    int detect_coll;
    46    int ubc_check;
    47    int reduced_round_coll;
    48    collision_block_callback callback;
    49  
    50    uint32_t ihv1[5];
    51    uint32_t ihv2[5];
    52    uint32_t m1[80];
    53    uint32_t m2[80];
    54    uint32_t states[80][5];
    55  };
    56  #endif
    57  void SHA1DCInit(SHA1_CTX*);
    58  void SHA1DCUpdate(SHA1_CTX*, const unsigned char*, unsigned);
    59  int SHA1DCFinal(unsigned char[20], SHA1_CTX*);
    60  
    61  #define SHA1Context SHA1_CTX
    62  #define SHA1Init SHA1DCInit
    63  #define SHA1Update SHA1DCUpdate
    64  #define SHA1Final SHA1DCFinal
    65  
    66  /*
    67  ** SHA1 Implementation #2: use the SHA1 algorithm built into SSL
    68  */
    69  #elif  defined(FOSSIL_ENABLE_SSL)
    70  
    71  # include <openssl/sha.h>
    72  # define SHA1Context SHA_CTX
    73  # define SHA1Init SHA1_Init
    74  # define SHA1Update SHA1_Update
    75  # define SHA1Final SHA1_Final
    76  
    77  /*
    78  ** SHA1 Implementation #3:  If none of the previous two SHA1
    79  ** algorithms work, there is this built-in.  This built-in was the
    80  ** original implementation used by Fossil.
    81  */
    82  #else
    83  /*
    84  ** The SHA1 implementation below is adapted from:
    85  **
    86  **  $NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $
    87  **  $OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $
    88  **
    89  ** SHA-1 in C
    90  ** By Steve Reid <steve@edmweb.com>
    91  ** 100% Public Domain
    92  */
    93  typedef struct SHA1Context SHA1Context;
    94  struct SHA1Context {
    95    unsigned int state[5];
    96    unsigned int count[2];
    97    unsigned char buffer[64];
    98  };
    99  
   100  /*
   101   * blk0() and blk() perform the initial expand.
   102   * I got the idea of expanding during the round function from SSLeay
   103   *
   104   * blk0le() for little-endian and blk0be() for big-endian.
   105   */
   106  #if __GNUC__ && (defined(__i386__) || defined(__x86_64__))
   107  /*
   108   * GCC by itself only generates left rotates.  Use right rotates if
   109   * possible to be kinder to dinky implementations with iterative rotate
   110   * instructions.
   111   */
   112  #define SHA_ROT(op, x, k) \
   113          ({ unsigned int y; asm(op " %1,%0" : "=r" (y) : "I" (k), "0" (x)); y; })
   114  #define rol(x,k) SHA_ROT("roll", x, k)
   115  #define ror(x,k) SHA_ROT("rorl", x, k)
   116  
   117  #else
   118  /* Generic C equivalent */
   119  #define SHA_ROT(x,l,r) ((x) << (l) | (x) >> (r))
   120  #define rol(x,k) SHA_ROT(x,k,32-(k))
   121  #define ror(x,k) SHA_ROT(x,32-(k),k)
   122  #endif
   123  
   124  
   125  
   126  
   127  
   128  #define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \
   129      |(rol(block[i],8)&0x00FF00FF))
   130  #define blk0be(i) block[i]
   131  #define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \
   132      ^block[(i+2)&15]^block[i&15],1))
   133  
   134  /*
   135   * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
   136   *
   137   * Rl0() for little-endian and Rb0() for big-endian.  Endianness is
   138   * determined at run-time.
   139   */
   140  #define Rl0(v,w,x,y,z,i) \
   141      z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2);
   142  #define Rb0(v,w,x,y,z,i) \
   143      z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2);
   144  #define R1(v,w,x,y,z,i) \
   145      z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2);
   146  #define R2(v,w,x,y,z,i) \
   147      z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2);
   148  #define R3(v,w,x,y,z,i) \
   149      z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2);
   150  #define R4(v,w,x,y,z,i) \
   151      z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2);
   152  
   153  /*
   154   * Hash a single 512-bit block. This is the core of the algorithm.
   155   */
   156  #define a qq[0]
   157  #define b qq[1]
   158  #define c qq[2]
   159  #define d qq[3]
   160  #define e qq[4]
   161  
   162  void SHA1Transform(unsigned int state[5], const unsigned char buffer[64])
   163  {
   164    unsigned int qq[5]; /* a, b, c, d, e; */
   165    static int one = 1;
   166    unsigned int block[16];
   167    memcpy(block, buffer, 64);
   168    memcpy(qq,state,5*sizeof(unsigned int));
   169  
   170    /* Copy context->state[] to working vars */
   171    /*
   172    a = state[0];
   173    b = state[1];
   174    c = state[2];
   175    d = state[3];
   176    e = state[4];
   177    */
   178  
   179    /* 4 rounds of 20 operations each. Loop unrolled. */
   180    if( 1 == *(unsigned char*)&one ){
   181      Rl0(a,b,c,d,e, 0); Rl0(e,a,b,c,d, 1); Rl0(d,e,a,b,c, 2); Rl0(c,d,e,a,b, 3);
   182      Rl0(b,c,d,e,a, 4); Rl0(a,b,c,d,e, 5); Rl0(e,a,b,c,d, 6); Rl0(d,e,a,b,c, 7);
   183      Rl0(c,d,e,a,b, 8); Rl0(b,c,d,e,a, 9); Rl0(a,b,c,d,e,10); Rl0(e,a,b,c,d,11);
   184      Rl0(d,e,a,b,c,12); Rl0(c,d,e,a,b,13); Rl0(b,c,d,e,a,14); Rl0(a,b,c,d,e,15);
   185    }else{
   186      Rb0(a,b,c,d,e, 0); Rb0(e,a,b,c,d, 1); Rb0(d,e,a,b,c, 2); Rb0(c,d,e,a,b, 3);
   187      Rb0(b,c,d,e,a, 4); Rb0(a,b,c,d,e, 5); Rb0(e,a,b,c,d, 6); Rb0(d,e,a,b,c, 7);
   188      Rb0(c,d,e,a,b, 8); Rb0(b,c,d,e,a, 9); Rb0(a,b,c,d,e,10); Rb0(e,a,b,c,d,11);
   189      Rb0(d,e,a,b,c,12); Rb0(c,d,e,a,b,13); Rb0(b,c,d,e,a,14); Rb0(a,b,c,d,e,15);
   190    }
   191    R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
   192    R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
   193    R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
   194    R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
   195    R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
   196    R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
   197    R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
   198    R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
   199    R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
   200    R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
   201    R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
   202    R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
   203    R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
   204    R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
   205    R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
   206    R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
   207  
   208    /* Add the working vars back into context.state[] */
   209    state[0] += a;
   210    state[1] += b;
   211    state[2] += c;
   212    state[3] += d;
   213    state[4] += e;
   214  }
   215  
   216  
   217  /*
   218   * SHA1Init - Initialize new context
   219   */
   220  static void SHA1Init(SHA1Context *context){
   221      /* SHA1 initialization constants */
   222      context->state[0] = 0x67452301;
   223      context->state[1] = 0xEFCDAB89;
   224      context->state[2] = 0x98BADCFE;
   225      context->state[3] = 0x10325476;
   226      context->state[4] = 0xC3D2E1F0;
   227      context->count[0] = context->count[1] = 0;
   228  }
   229  
   230  
   231  /*
   232   * Run your data through this.
   233   */
   234  static void SHA1Update(
   235    SHA1Context *context,
   236    const unsigned char *data,
   237    unsigned int len
   238  ){
   239      unsigned int i, j;
   240  
   241      j = context->count[0];
   242      if ((context->count[0] += len << 3) < j)
   243          context->count[1] += (len>>29)+1;
   244      j = (j >> 3) & 63;
   245      if ((j + len) > 63) {
   246          (void)memcpy(&context->buffer[j], data, (i = 64-j));
   247          SHA1Transform(context->state, context->buffer);
   248          for ( ; i + 63 < len; i += 64)
   249              SHA1Transform(context->state, &data[i]);
   250          j = 0;
   251      } else {
   252          i = 0;
   253      }
   254      (void)memcpy(&context->buffer[j], &data[i], len - i);
   255  }
   256  
   257  
   258  /*
   259   * Add padding and return the message digest.
   260   */
   261  static void SHA1Final(unsigned char *digest, SHA1Context *context){
   262      unsigned int i;
   263      unsigned char finalcount[8];
   264  
   265      for (i = 0; i < 8; i++) {
   266          finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
   267           >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
   268      }
   269      SHA1Update(context, (const unsigned char *)"\200", 1);
   270      while ((context->count[0] & 504) != 448)
   271          SHA1Update(context, (const unsigned char *)"\0", 1);
   272      SHA1Update(context, finalcount, 8);  /* Should cause a SHA1Transform() */
   273  
   274      if (digest) {
   275          for (i = 0; i < 20; i++)
   276              digest[i] = (unsigned char)
   277                  ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
   278      }
   279  }
   280  #endif /* Built-in SHA1 implemenation */
   281  
   282  /*
   283  ** Convert a digest into base-16.  digest should be declared as
   284  ** "unsigned char digest[20]" in the calling function.  The SHA1
   285  ** digest is stored in the first 20 bytes.  zBuf should
   286  ** be "char zBuf[41]".
   287  */
   288  static void DigestToBase16(unsigned char *digest, char *zBuf){
   289    static const char zEncode[] = "0123456789abcdef";
   290    int ix;
   291  
   292    for(ix=0; ix<20; ix++){
   293      *zBuf++ = zEncode[(*digest>>4)&0xf];
   294      *zBuf++ = zEncode[*digest++ & 0xf];
   295    }
   296    *zBuf = '\0';
   297  }
   298  
   299  /*
   300  ** The state of a incremental SHA1 checksum computation.  Only one
   301  ** such computation can be underway at a time, of course.
   302  */
   303  static SHA1Context incrCtx;
   304  static int incrInit = 0;
   305  
   306  /*
   307  ** Add more text to the incremental SHA1 checksum.
   308  */
   309  void sha1sum_step_text(const char *zText, int nBytes){
   310    if( !incrInit ){
   311      SHA1Init(&incrCtx);
   312      incrInit = 1;
   313    }
   314    if( nBytes<=0 ){
   315      if( nBytes==0 ) return;
   316      nBytes = strlen(zText);
   317    }
   318    SHA1Update(&incrCtx, (unsigned char*)zText, nBytes);
   319  }
   320  
   321  /*
   322  ** Add the content of a blob to the incremental SHA1 checksum.
   323  */
   324  void sha1sum_step_blob(Blob *p){
   325    sha1sum_step_text(blob_buffer(p), blob_size(p));
   326  }
   327  
   328  /*
   329  ** Finish the incremental SHA1 checksum.  Store the result in blob pOut
   330  ** if pOut!=0.  Also return a pointer to the result.
   331  **
   332  ** This resets the incremental checksum preparing for the next round
   333  ** of computation.  The return pointer points to a static buffer that
   334  ** is overwritten by subsequent calls to this function.
   335  */
   336  char *sha1sum_finish(Blob *pOut){
   337    unsigned char zResult[20];
   338    static char zOut[41];
   339    sha1sum_step_text(0,0);
   340    SHA1Final(zResult, &incrCtx);
   341    incrInit = 0;
   342    DigestToBase16(zResult, zOut);
   343    if( pOut ){
   344      blob_zero(pOut);
   345      blob_append(pOut, zOut, 40);
   346    }
   347    return zOut;
   348  }
   349  
   350  
   351  /*
   352  ** Compute the SHA1 checksum of a file on disk.  Store the resulting
   353  ** checksum in the blob pCksum.  pCksum is assumed to be initialized.
   354  **
   355  ** Return the number of errors.
   356  */
   357  int sha1sum_file(const char *zFilename, int eFType, Blob *pCksum){
   358    FILE *in;
   359    SHA1Context ctx;
   360    unsigned char zResult[20];
   361    char zBuf[10240];
   362  
   363    if( eFType==RepoFILE && file_islink(zFilename) ){
   364      /* Instead of file content, return sha1 of link destination path */
   365      Blob destinationPath;
   366      int rc;
   367  
   368      blob_read_link(&destinationPath, zFilename);
   369      rc = sha1sum_blob(&destinationPath, pCksum);
   370      blob_reset(&destinationPath);
   371      return rc;
   372    }
   373  
   374    in = fossil_fopen(zFilename,"rb");
   375    if( in==0 ){
   376      return 1;
   377    }
   378    SHA1Init(&ctx);
   379    for(;;){
   380      int n;
   381      n = fread(zBuf, 1, sizeof(zBuf), in);
   382      if( n<=0 ) break;
   383      SHA1Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
   384    }
   385    fclose(in);
   386    blob_zero(pCksum);
   387    blob_resize(pCksum, 40);
   388    SHA1Final(zResult, &ctx);
   389    DigestToBase16(zResult, blob_buffer(pCksum));
   390    return 0;
   391  }
   392  
   393  /*
   394  ** Compute the SHA1 checksum of a blob in memory.  Store the resulting
   395  ** checksum in the blob pCksum.  pCksum is assumed to be either
   396  ** uninitialized or the same blob as pIn.
   397  **
   398  ** Return the number of errors.
   399  */
   400  int sha1sum_blob(const Blob *pIn, Blob *pCksum){
   401    SHA1Context ctx;
   402    unsigned char zResult[20];
   403  
   404    SHA1Init(&ctx);
   405    SHA1Update(&ctx, (unsigned char*)blob_buffer(pIn), blob_size(pIn));
   406    if( pIn==pCksum ){
   407      blob_reset(pCksum);
   408    }else{
   409      blob_zero(pCksum);
   410    }
   411    blob_resize(pCksum, 40);
   412    SHA1Final(zResult, &ctx);
   413    DigestToBase16(zResult, blob_buffer(pCksum));
   414    return 0;
   415  }
   416  
   417  /*
   418  ** Compute the SHA1 checksum of a zero-terminated string.  The
   419  ** result is held in memory obtained from mprintf().
   420  */
   421  char *sha1sum(const char *zIn){
   422    SHA1Context ctx;
   423    unsigned char zResult[20];
   424    char zDigest[41];
   425  
   426    SHA1Init(&ctx);
   427    SHA1Update(&ctx, (unsigned const char*)zIn, strlen(zIn));
   428    SHA1Final(zResult, &ctx);
   429    DigestToBase16(zResult, zDigest);
   430    return mprintf("%s", zDigest);
   431  }
   432  
   433  /*
   434  ** Convert a cleartext password for a specific user into a SHA1 hash.
   435  **
436 ** The algorithm here is: 437 ** 438 ** SHA1( project-code + "/" + login + "/" + password ) 439 ** 440 ** In words: The users login name and password are appended to the 441 ** project ID code and the SHA1 hash of the result is computed.
442 ** 443 ** The result of this function is the shared secret used by a client 444 ** to authenticate to a server for the sync protocol. It is also the 445 ** value stored in the USER.PW field of the database. By mixing in the 446 ** login name and the project id with the hash, different shared secrets 447 ** are obtained even if two users select the same password, or if a 448 ** single user selects the same password for multiple projects. 449 */ 450 char *sha1_shared_secret( 451 const char *zPw, /* The password to encrypt */ 452 const char *zLogin, /* Username */ 453 const char *zProjCode /* Project-code. Use built-in project code if NULL */ 454 ){ 455 static char *zProjectId = 0; 456 SHA1Context ctx; 457 unsigned char zResult[20]; 458 char zDigest[41]; 459 460 SHA1Init(&ctx); 461 if( zProjCode==0 ){ 462 if( zProjectId==0 ){ 463 zProjectId = db_get("project-code", 0); 464 465 /* On the first xfer request of a clone, the project-code is not yet 466 ** known. Use the cleartext password, since that is all we have. 467 */ 468 if( zProjectId==0 ){ 469 return mprintf("%s", zPw); 470 } 471 } 472 zProjCode = zProjectId; 473 } 474 SHA1Update(&ctx, (unsigned char*)zProjCode, strlen(zProjCode)); 475 SHA1Update(&ctx, (unsigned char*)"/", 1); 476 SHA1Update(&ctx, (unsigned char*)zLogin, strlen(zLogin)); 477 SHA1Update(&ctx, (unsigned char*)"/", 1); 478 SHA1Update(&ctx, (unsigned const char*)zPw, strlen(zPw)); 479 SHA1Final(zResult, &ctx); 480 DigestToBase16(zResult, zDigest); 481 return mprintf("%s", zDigest); 482 } 483 484 /* 485 ** Implement the shared_secret() SQL function. shared_secret() takes two or 486 ** three arguments; the third argument is optional. 487 ** 488 ** (1) The cleartext password 489 ** (2) The login name 490 ** (3) The project code 491 ** 492 ** Returns sha1($password/$login/$projcode). 493 */ 494 void sha1_shared_secret_sql_function( 495 sqlite3_context *context, 496 int argc, 497 sqlite3_value **argv 498 ){ 499 const char *zPw; 500 const char *zLogin; 501 const char *zProjid; 502 503 assert( argc==2 || argc==3 ); 504 zPw = (const char*)sqlite3_value_text(argv[0]); 505 if( zPw==0 || zPw[0]==0 ) return; 506 zLogin = (const char*)sqlite3_value_text(argv[1]); 507 if( zLogin==0 ) return; 508 if( argc==3 ){ 509 zProjid = (const char*)sqlite3_value_text(argv[2]); 510 if( zProjid && zProjid[0]==0 ) zProjid = 0; 511 }else{ 512 zProjid = 0; 513 } 514 sqlite3_result_text(context, sha1_shared_secret(zPw, zLogin, zProjid), -1, 515 fossil_free); 516 } 517 518 /* 519 ** COMMAND: sha1sum* 520 ** 521 ** Usage: %fossil sha1sum FILE... 522 ** 523 ** Compute an SHA1 checksum of all files named on the command-line. 524 ** If a file is named "-" then take its content from standard input. 525 ** Options: 526 ** 527 ** -h, --dereference If FILE is a symbolic link, compute the hash 528 ** on the object that the link points to. Normally, 529 ** the hash is over the name of the object that 530 ** the link points to. 531 */ 532 void sha1sum_test(void){ 533 int i; 534 Blob in; 535 Blob cksum; 536 int eFType = SymFILE; 537 if( find_option("dereference","h",0)!=0 ){ 538 eFType = ExtFILE; 539 } 540 541 for(i=2; i<g.argc; i++){ 542 blob_init(&cksum, "************** not found ***************", -1); 543 if( g.argv[i][0]=='-' && g.argv[i][1]==0 ){ 544 blob_read_from_channel(&in, stdin, -1); 545 sha1sum_blob(&in, &cksum); 546 }else{ 547 sha1sum_file(g.argv[i], eFType, &cksum); 548 } 549 fossil_print("%s %s\n", blob_str(&cksum), g.argv[i]); 550 blob_reset(&cksum); 551 } 552 }