/* passwd.c  --  Generates a SHA512 hash of a clear-text password
 *
 *  Parts of this code is released into the Public Domain by
 *  Ulrich Drepper <drepper@redhat.com> and adopted by
 *  David Sommerseth <dazo@users.sourceforge.net> 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 - 2012
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  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.
 *
 */

/**
 * @file   passwd.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @author Ulrich Drepper <drepper@redhat.com>
 * @date   2009-03-21
 *
 * @brief  Functions for generating SHA512 hashes from clear-text values.  Parts of this
 *         code is based on Ulrich Dreppers paper for implementing SHA512 hashing in glibc.
 *
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#ifdef HAVE_SYS_ENDIAN_H
# include <sys/endian.h>
#else
# include <endian.h>
#endif /* HAVE_SYS_ENDIAN_H */
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <assert.h>
#include <time.h>
#include <unistd.h>

#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"

#define DEFAULT_SALT_LEN 32	/**< Default hash salt length */
#define MAX_SALT_LEN 255	/**< Maximum hash salt length */

#define ROUNDS_DEFAULT_MIN 5000 /**< Default minimum hashing rounds (may be changed in runtime config)*/
#define ROUNDS_DEFAULT_MAX 7500 /**< Default maximum hashing rounds (may be changed in runtime config)*/
#define ROUNDS_MIN 1000		/**< Absolutely minimum hashing rounds */
#define ROUNDS_MAX 999999999	/**< Absolutely maximum hashing rounds */

/**
 *Table with characters for base64 transformation.
*/
static const char b64t[64] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";


/**
 * Generates a phase2 salt value from a password.
 *
 * @param pwd  Input hash
 *
 * @return Returns an int value containing the phase2 salt information
 */
static 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;
}


/**
 *  Packs the hashing rounds value and salt length as a 8 byte hex value, and "scrambled" with
 *  a phase2 salt information.
 *
 * @param buf     Return buffer where the salt info will be returned
 * @param buflen  Size of the buffer
 * @param rounds  Number of hashing rounds
 * @param saltlen Length of the SHA512 salt
 * @param pwd     Password of the user
 *
 * @return Returns the length of the salt information in bytes.
 */
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);
}


/**
 * This function will unpack the salt information and "unscramble" it with a given password
 *
 * @param insalt  Input eurephia SHA512 salt string
 * @param pwd     Users password
 *
 * @return Returns the decoded salt information, containing hashing rounds and salt length.
 */
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;
        }
}


/**
 * Generates a number of random characters, used to create an even more unpredictable hashing salt
 *
 * @param ctx      eurephiaCTX
 * @param saltstr  Return buffer where the salt will be placed (char *)
 * @param len      Size of the buffer
 *
 * @return Returns 1 on success, otherwise 0
 */
int gen_randsaltstr(eurephiaCTX *ctx, char *saltstr, int len) {
        static const char randchars[] = "7+q2wertyuiopasd5fghj1kl<zxcvbnm,3.-!#%&/()9=?ZXCVBNM;:_ASD4FGHJK6L*QWE8RTYUI0OP>@£$\0";
        unsigned char *rand = NULL, *ptr2 = NULL;
        char *ptr = NULL;
        int i = 0;

        rand = (unsigned char *) malloc_nullsafe(ctx, len+2);
        assert(rand != NULL );
        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(ctx, rand);
        return 1;
}


/**
 *  Internal function used by sha512_crytp_r().  Converts 24 bits of data into base64 format.
 *
 * @param B2
 * @param B1
 * @param B0
 * @param N
 */
#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)


/**
 * Internal SHA512 hashing function.  Does the real hashing job
 *
 * @param key            The password of the user
 * @param salt           Salt to be used when generating the SHA512 hash
 * @param maxrounds_cfg  Maximum configured hashing rounds
 * @param buffer         Buffer where to put the SHA512 result
 * @param buflen         Size of the buffer
 *
 * @return  Returns a pointer to the buffer, or NULL on failure.
 */
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 multiplying 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
        // brute-force attacks directly on eurephia, we add 1 seconds sleep.
        //
        if( rounds > (maxrounds_cfg * 1.5) ) {
                sleep(1);
                return NULL;
        }

        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 = memcpy (cp, temp_result, 64);
                cp += 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 = memcpy (cp, temp_result, 64);
                cp += 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);

        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 SHA512 password hashing for eurephia passwords.  Suitable when passwords needs to be
 * stored on disk.
 *
 * @param ctx  eurephiaCTX
 * @param key  Users password
 * @param salt Salt to be used when validating the password.  To generate a new SHA512 hash, set
 *             this parameter to NULL
 *
 * @return Returns a string to a buffer containing the SHA512 hash.  This buffer must be cleared and
 *         freed when no longer needed.
 */
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
        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_nullsafe(ctx, buflen);
        assert(buffer != NULL);
        mlock(buffer, buflen);
        mlock(&saltstr, MAX_SALT_LEN+22);

        // 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 = NULL;
                int minrounds = 0, rounds = ROUNDS_DEFAULT_MAX, loop = 0, saltlen = 0;

                // Get current salt length
                saltlen = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config,
                                                                   "passwordhash_salt_length")),
                                          DEFAULT_SALT_LEN);

                tmp = malloc_nullsafe(ctx, saltlen+2);
                assert(tmp != NULL);
                mlock(tmp, saltlen+2);
                memset(&saltstr, 0, MAX_SALT_LEN+22);

                // 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 >= 1000 ) {
                        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);
                munlock(tmp, saltlen+2);
                free_nullsafe(ctx, tmp);
        } else {
                // If we have a salt, use it
                snprintf(saltstr, MAX_SALT_LEN+20, "%s%c", salt, 0);
        }
        // For some reason, if not strdup()ing 'buffer' and returning buffer it causes a memory leak
        result = strdup_nullsafe(sha512_crypt_r(key, saltstr, maxrounds, buffer, buflen));
        memset(buffer, 0, buflen);
        munlock(buffer, buflen);
        free_nullsafe(NULL, buffer);
        munlock(&saltstr, MAX_SALT_LEN+22);
        return result;
}


/**
 * Very quick SHA512 hashing algorithm, to be used only when hashing is static and not suitable for
 * storing of password hashes.
 *
 * @param salt  Salt to be used when generating the hashing
 * @param pwd   Value to be hashed.
 *
 * @return  Returns a pointer to buffer containing the SHA512 hash.  This buffer must be cleared and freed
 *          when no longer needed.
 */

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_nullsafe(NULL, strlen_nullsafe(salt) + len + 10);
                sprintf(tmp, "%s%s", pwd, salt);
        } else {
                tmp = strdup_nullsafe(pwd);
        }
        mlock(tmp, strlen_nullsafe(tmp));

        // Generate SHA512 hash of password
        mlock(&sha, sizeof(SHA512Context));
        memset(&sha, 0, sizeof(SHA512Context));
        mlock(&sha_res, sizeof(sha_res));
        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_nullsafe(NULL, (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));
        munlock(&sha, sizeof(SHA512Context));
        munlock(&sha_res, sizeof(sha_res));

        len = strlen_nullsafe(tmp);
        memset(tmp, 0, len);
        munlock(tmp, len);
        free_nullsafe(NULL, tmp);

        return ret;
}
