summaryrefslogtreecommitdiffstats
path: root/common/passwd.c
blob: 200660217b31e02608a889abb4885f134fec96e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/* 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 - Copyright (C) 2008  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.
 *
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <endian.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <sys/param.h>
#include <sys/types.h>
#include <assert.h>
#include <time.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"


// 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<zxcvbnm,3.-!#%&/()9=?ZXCVBNM;:_ASD4FGHJK6L*QWE8RTYUI0OP>@£$\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, 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);

        //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 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);

        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 min = 0, max = 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/max rounds for hashing
                min = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config, "passwordhash_rounds_min")),
                                      ROUNDS_DEFAULT_MIN);
                max = defaultIntValue(atoi_nullsafe(eGet_value(ctx->dbc->config, "passwordhash_rounds_max")),
                                      ROUNDS_DEFAULT_MAX);

                // Loop until we have a random number we'd like to use as our hashing rounds value
                do {
                        rounds = rand() % max;
                        loop++;
                } while( ((rounds < min) || (rounds > max)) && (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, 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;
}