/* passwd.c -- Generates a SHA512 hash of a clear-text password * * Parts of this code is released into the Public Domain by * Ulrich Drepper and adopted by * David Sommerseth to match the * needs in eurephia. The original work can be found here: * * http://people.redhat.com/drepper/sha-crypt.html * * GPLv2 only - Copyright (C) 2008, 2009 * David Sommerseth * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include "eurephia_nullsafe.h" #include "eurephia_context.h" #include "eurephia_log.h" #include "eurephia_values.h" #include "randstr.h" #include "passwd.h" #include "sha512.h" // default and maximum allowed salt length #define DEFAULT_SALT_LEN 32 #define MAX_SALT_LEN 255 // When randomising rounds, this is the default scope #define ROUNDS_DEFAULT_MIN 5000 #define ROUNDS_DEFAULT_MAX 7500 // Min/Max rounds boundaries #define ROUNDS_MIN 1000 #define ROUNDS_MAX 999999999 /* Table with characters for base64 transformation. */ static const char b64t[64] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; inline unsigned int get_salt_p2(const char *pwd) { int n = 0; long int saltinfo_p2 = 0, t = 0; for( n = 0; n < strlen_nullsafe(pwd); n++ ) { t += pwd[n]; } for( n = 0; n < 4; n++ ) { saltinfo_p2 <<= 8; saltinfo_p2 += (strlen_nullsafe(pwd) ^ (t % 0xff)); } return saltinfo_p2; } int pack_saltinfo(char *buf, int buflen, int rounds, int saltlen, const char *pwd) { assert((buf != NULL) && (buflen > 0)); snprintf(buf, buflen, "%08x%c", (unsigned int)(((rounds<<8)+saltlen) ^ 0xAAAAAAAA) ^ get_salt_p2(pwd), 0); return strlen_nullsafe(buf); } unsigned int unpack_saltinfo(const char *insalt, const char *pwd) { unsigned int in_salt_prefix = 0; assert(insalt != NULL && pwd != NULL); if( sscanf(insalt, "%08x", &in_salt_prefix) > -1 ) { long int regen_p2 = in_salt_prefix ^ get_salt_p2(pwd); return regen_p2 ^ 0xAAAAAAAA; } else { return -1; } } int gen_randsaltstr(eurephiaCTX *ctx, char *saltstr, int len) { static const char randchars[] = "7+q2wertyuiopasd5fghj1kl@£$\0"; unsigned char *rand = NULL, *ptr2 = NULL; char *ptr = NULL; int i = 0; rand = (unsigned char *) malloc(len+2); assert(rand != NULL ); memset(rand, 0, len+2); if( !eurephia_randstring(ctx, rand, len) ) { return 0; } ptr = saltstr; ptr2 = rand; memset(ptr, 0, len); for( i = 0; i < len; i++ ) { *ptr = randchars[(*ptr2 % 81)]; ptr++; ptr2++; } free_nullsafe(rand); return 1; } static char *sha512_crypt_r(const char *key, const char *salt, size_t maxrounds_cfg, char *buffer, int buflen) { unsigned char alt_result[64] __attribute__ ((__aligned__ (__alignof__ (uint64_t)))); unsigned char temp_result[64] __attribute__ ((__aligned__ (__alignof__ (uint64_t)))); SHA512Context ctx; SHA512Context alt_ctx; unsigned int saltinfo = 0; size_t salt_len; size_t key_len; size_t cnt; size_t rounds; char *cp; char *copied_key = NULL; char *copied_salt = NULL; char *p_bytes; char *s_bytes; // Extract salt information saltinfo = unpack_saltinfo(salt, key); salt_len = saltinfo & 0x000000ff; rounds = MAX(ROUNDS_MIN, MIN(((saltinfo & 0xffffff00) >> 8), ROUNDS_MAX)); key_len = strlen (key); // If the decoded rounds value from the salt is bigger than the // the maximum configured rounds * 1.5, then the password is definitely wrong. // // The drawback is if the maxrounds later on is changed to a value which is: // passwordsalt_rounds > maxrounds_cfg * 1.5 // these passwords will be invalidated by that change. This is considered // to be a feature and not a bug. The reason for mulitiplying by 1.5, is to // allow a little room for a degrading max rounds. // // Without this fix, a wrong password might take several seconds or minutes to // calculate. This behaviour is not wanted as that wastes CPU cycles on something // we know is wrong. But to avoid quiting too quickly and to slow down // bruteforce attacks directly on eurephia, we add 1 seconds sleep. // if( rounds > (maxrounds_cfg * 1.5) ) { sleep(1); return NULL; } //printf("%-8.8s == (%ld, %i) [%02x, %06x]\n", // salt, (long int)rounds, (int)salt_len, (int)rounds, (int)salt_len); if ((key - (char *) 0) % __alignof__ (uint64_t) != 0) { char *tmp = (char *) alloca (key_len + __alignof__ (uint64_t)); key = copied_key = memcpy (tmp + __alignof__ (uint64_t) - (tmp - (char *) 0) % __alignof__ (uint64_t), key, key_len); } if ((salt - (char *) 0) % __alignof__ (uint64_t) != 0) { char *tmp = (char *) alloca (salt_len + __alignof__ (uint64_t)); salt = copied_salt = memcpy (tmp + __alignof__ (uint64_t) - (tmp - (char *) 0) % __alignof__ (uint64_t), salt, salt_len); } /* Prepare for the real work. */ SHA512Init (&ctx); /* Add the key string. */ SHA512Update (&ctx, key, key_len); /* The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character (for compatibility with existing implementations). */ SHA512Update (&ctx, salt, salt_len); /* Compute alternate SHA512 sum with input KEY, SALT, and KEY. The final result will be added to the first context. */ SHA512Init (&alt_ctx); /* Add key. */ SHA512Update (&alt_ctx, key, key_len); /* Add salt. */ SHA512Update (&alt_ctx, salt, salt_len); /* Add key again. */ SHA512Update (&alt_ctx, key, key_len); /* Now get result of this (64 bytes) and add it to the other context. */ SHA512Final (&alt_ctx, alt_result); /* Add for any character in the key one byte of the alternate sum. */ for (cnt = key_len; cnt > 64; cnt -= 64) { SHA512Update (&ctx, alt_result, 64); } SHA512Update (&ctx, alt_result, cnt); /* Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0 the key. */ for (cnt = key_len; cnt > 0; cnt >>= 1) { if ((cnt & 1) != 0) { SHA512Update (&ctx, alt_result, 64); } else { SHA512Update (&ctx, key, key_len); } } /* Create intermediate result. */ SHA512Final (&ctx, alt_result); /* Start computation of P byte sequence. */ SHA512Init (&alt_ctx); /* For every character in the password add the entire password. */ for (cnt = 0; cnt < key_len; ++cnt) { SHA512Update (&alt_ctx, key, key_len); } /* Finish the digest. */ SHA512Final (&alt_ctx, temp_result); /* Create byte sequence P. */ cp = p_bytes = alloca (key_len); for (cnt = key_len; cnt >= 64; cnt -= 64) { cp = mempcpy (cp, temp_result, 64); } memcpy (cp, temp_result, cnt); /* Start computation of S byte sequence. */ SHA512Init (&alt_ctx); /* For every character in the password add the entire password. */ for (cnt = 0; cnt < 16 + alt_result[0]; ++cnt) { SHA512Update (&alt_ctx, salt, salt_len); } /* Finish the digest. */ SHA512Final (&alt_ctx, temp_result); /* Create byte sequence S. */ cp = s_bytes = alloca (salt_len); for (cnt = salt_len; cnt >= 64; cnt -= 64) { cp = mempcpy (cp, temp_result, 64); } memcpy (cp, temp_result, cnt); /* Repeatedly run the collected hash value through SHA512 to burn CPU cycles. */ for (cnt = 0; cnt < rounds; ++cnt) { /* New context. */ SHA512Init (&ctx); /* Add key or last result. */ if ((cnt & 1) != 0) { SHA512Update (&ctx, p_bytes, key_len); } else { SHA512Update (&ctx, alt_result, 64); } /* Add salt for numbers not divisible by 3. */ if (cnt % 3 != 0) { SHA512Update (&ctx, s_bytes, salt_len); } /* Add key for numbers not divisible by 7. */ if (cnt % 7 != 0) { SHA512Update (&ctx, p_bytes, key_len); } /* Add key or last result. */ if ((cnt & 1) != 0) { SHA512Update (&ctx, alt_result, 64); } else { SHA512Update (&ctx, p_bytes, key_len); } /* Create intermediate result. */ SHA512Final (&ctx, alt_result); } /* Now we can construct the result string. It consists of three parts. */ cp = __stpncpy (buffer, salt, MIN ((size_t) MAX (0, buflen), salt_len)); buflen -= MIN ((size_t) MAX (0, buflen), salt_len); #define b64_from_24bit(B2, B1, B0, N) \ do { \ unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \ int n = (N); \ while (n-- > 0 && buflen > 0) { \ *cp++ = b64t[w & 0x3f]; \ --buflen; \ w >>= 6; \ } \ } while (0) b64_from_24bit (alt_result[0], alt_result[21], alt_result[42], 4); b64_from_24bit (alt_result[22], alt_result[43], alt_result[1], 4); b64_from_24bit (alt_result[44], alt_result[2], alt_result[23], 4); b64_from_24bit (alt_result[3], alt_result[24], alt_result[45], 4); b64_from_24bit (alt_result[25], alt_result[46], alt_result[4], 4); b64_from_24bit (alt_result[47], alt_result[5], alt_result[26], 4); b64_from_24bit (alt_result[6], alt_result[27], alt_result[48], 4); b64_from_24bit (alt_result[28], alt_result[49], alt_result[7], 4); b64_from_24bit (alt_result[50], alt_result[8], alt_result[29], 4); b64_from_24bit (alt_result[9], alt_result[30], alt_result[51], 4); b64_from_24bit (alt_result[31], alt_result[52], alt_result[10], 4); b64_from_24bit (alt_result[53], alt_result[11], alt_result[32], 4); b64_from_24bit (alt_result[12], alt_result[33], alt_result[54], 4); b64_from_24bit (alt_result[34], alt_result[55], alt_result[13], 4); b64_from_24bit (alt_result[56], alt_result[14], alt_result[35], 4); b64_from_24bit (alt_result[15], alt_result[36], alt_result[57], 4); b64_from_24bit (alt_result[37], alt_result[58], alt_result[16], 4); b64_from_24bit (alt_result[59], alt_result[17], alt_result[38], 4); b64_from_24bit (alt_result[18], alt_result[39], alt_result[60], 4); b64_from_24bit (alt_result[40], alt_result[61], alt_result[19], 4); b64_from_24bit (alt_result[62], alt_result[20], alt_result[41], 4); b64_from_24bit (0, 0, alt_result[63], 2); if (buflen <= 0) { errno = ERANGE; buffer = NULL; } else { *cp = '\0'; /* Terminate the string. */ } /* Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps cannot get any information. We do it in this way to clear correct_words[] inside the SHA512 implementation as well. */ SHA512Init (&ctx); SHA512Final (&ctx, alt_result); memset (temp_result, '\0', sizeof (temp_result)); memset (p_bytes, '\0', key_len); memset (s_bytes, '\0', salt_len); memset (&ctx, '\0', sizeof (ctx)); memset (&alt_ctx, '\0', sizeof (alt_ctx)); if (copied_key != NULL) { memset (copied_key, '\0', key_len); } if (copied_salt != NULL) { memset (copied_salt, '\0', salt_len); } return buffer; } /* The main password hashing for eurephia passwords */ char *eurephia_pwd_crypt(eurephiaCTX *ctx, const char *key, const char *salt) { /* We don't want to have an arbitrary limit in the size of the password. We can compute an upper bound for the size of the result in advance and so we can prepare the buffer we pass to `sha512_crypt_r'. */ char *buffer = NULL, *result = NULL; int buflen = (MAX_SALT_LEN + 20 + 1 + 86 + 1); char saltinfo[20], saltstr[MAX_SALT_LEN+22]; // saltstr will also contain saltinfo int saltlen = 0; static size_t maxrounds = 0; static int srand_init = 0; assert( (ctx != NULL) && (ctx->dbc != NULL) ); // Init a simple random generator if( srand_init == 0 ) { srand( (unsigned int) time(NULL) ); } buffer = (char *) malloc(buflen); assert(buffer != NULL); memset(buffer, 0, buflen); // Get default max rounds for hashing if( maxrounds == 0 ) { maxrounds = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config, "passwordhash_rounds_max")), ROUNDS_DEFAULT_MAX); } if( salt == NULL ) { // If we do not have salt, create salt info char tmp[saltlen+2]; memset(&saltstr, 0, MAX_SALT_LEN+22); memset(&tmp, 0, saltlen+2); int minrounds = 0, rounds = ROUNDS_DEFAULT_MAX, loop = 0; if( saltlen == 0 ) { // Get current salt length saltlen = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config, "passwordhash_salt_length")), DEFAULT_SALT_LEN); } // Get default min rounds for hashing minrounds = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config, "passwordhash_rounds_min")), ROUNDS_DEFAULT_MIN); // Loop until we have a random number we'd like to use as our hashing rounds value do { rounds = rand() % maxrounds; loop++; } while( ((rounds < minrounds) || (rounds > maxrounds)) && (loop < 1000)) ; if( loop > 10000 ) { eurephia_log(ctx, LOG_FATAL, 0, "Could not get a valid random number for hashing after %i rounds", 1000); return NULL; } // Get random data for our salt if( gen_randsaltstr(ctx, tmp, saltlen) == 0 ) { return NULL; }; // Prepare a salt package memset(&saltinfo, 0, 20); pack_saltinfo(saltinfo, 18, rounds, saltlen, key); strncpy(saltstr, saltinfo, strlen(saltinfo)); strncat(saltstr, tmp, saltlen - strlen(saltinfo)); memset(&tmp, 0, saltlen+2); } else { // If we have a salt, use it snprintf(saltstr, MAX_SALT_LEN+20, "%s%c", salt, 0); } result = sha512_crypt_r(key, saltstr, maxrounds, buffer, buflen); return result; } char *eurephia_quick_hash(const char *salt, const char *pwd) { SHA512Context sha; uint8_t sha_res[SHA512_HASH_SIZE]; char *ret = NULL, *ptr = NULL, *tmp = NULL; unsigned len = 0, i; len = strlen_nullsafe(pwd); if( (pwd == NULL) && (len == 0) ) { return NULL; } if( salt != NULL ) { tmp = (char *) malloc(strlen_nullsafe(salt) + len + 2); memset(tmp, 0, strlen_nullsafe(salt) + len + 2); sprintf(tmp, "%s%s", pwd, salt); } else { tmp = strdup_nullsafe(pwd); } // Generate SHA512 hash of password memset(&sha, 0, sizeof(SHA512Context)); memset(&sha_res, 0, sizeof(sha_res)); SHA512Init(&sha); SHA512Update(&sha, tmp, len); SHA512Final(&sha, sha_res); // Allocate memory for the return buffer ret = (char *) malloc((SHA512_HASH_SIZE*2)+3); memset(ret, 0,(SHA512_HASH_SIZE*2)+3); ptr = ret; // Generate a readable string of the hash for( i = 0; i < SHA512_HASH_SIZE; i++ ) { sprintf(ptr, "%02x", sha_res[i]); ptr += 2; } // Cleanup - remove hash data from memory memset(&sha, 0, sizeof(SHA512Context)); memset(&sha_res, 0, sizeof(sha_res)); free_nullsafe(tmp); return ret; } #ifdef BENCHMARK // This function is only used by the eurephia_init program to benchmark // the SHA512 performance, to suggest recommended minimum and maximum // hashing rounds. void benchmark_hashing(int rounds) { char *buffer = NULL; char *pwdhash = NULL; static char randstr[34]; static int rand_set = 0; char pwdsalt[64], saltstr[32]; // Get random data for our salt if( rand_set == 0 ) { memset(&randstr, 0, 34); if( gen_randsaltstr(NULL, randstr, 32) == 0 ) { fprintf(stderr, "Could not retrieve enough random data for hashing"); exit(19); }; rand_set = 1; } // Prepare a salt package memset(&pwdsalt, 0, 64); memset(&saltstr, 0, 32); pack_saltinfo(saltstr, 30, rounds, 32, "benchmarkpassword"); strncpy(pwdsalt, saltstr, strlen(saltstr)); strncat(pwdsalt, randstr, 62 - strlen(saltstr)); memset(&randstr, 0, 32); buffer = (char *) malloc(1024); assert( buffer != NULL ); memset(buffer, 0, 1024); pwdhash = sha512_crypt_r("benchmarkpassword", pwdsalt, ROUNDS_MAX, buffer, 1024); free_nullsafe(buffer); } #endif