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
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright (c) 2018-2026, Stefan Meislinger <sm@opengate.at>                |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/encode/passwords.h"
#include "gate/results.h"
#include "gate/strings.h"
#include "gate/randomgen.h"
#include "gate/encode/sha256hash.h"
#include "gate/encode/base64.h"

#if defined(GATE_SYS_POSIX)
#   define GATE_ENCODE_CRYPT_IMPL 1
#endif


static void generate_salt(char salt[16])
{
    gate_randomsession_t rand_session;
    gate_result_t result;
    static gate_string_t const valid_chars = GATE_STRING_INIT_STATIC("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
    char const* valid_chars_ptr = gate_string_ptr(&valid_chars, 0);
    gate_size_t const valid_chars_len = gate_string_length(&valid_chars);

    result = gate_randomgenerator_create(&rand_session);
    if (GATE_SUCCEEDED(result))
    {
        gate_uint64_t num = 0;
        size_t n;
        for(n = 0; n != 16; ++n)
        {
            gate_size_t pos;
            gate_randomgenerator_get_num(&rand_session, &num);
            pos = num % valid_chars_len;
            salt[n] = valid_chars_ptr[pos];
        }
        gate_randomgenerator_destroy(&rand_session);
    }
}

#if defined(GATE_ENCODE_CRYPT_IMPL)

#include <unistd.h>
#include "gate/libraries.h"
#include "gate/platforms.h"

typedef char*(*crypt_func_t)(char const* key, char const* salt);

static crypt_func_t load_libcrypt()
{
    static crypt_func_t crypt_func = NULL;

    if(crypt_func != NULL)
    {
        return crypt_func;
    }
    else
    {
        static gate_library_t lib_libcrypt = NULL;
        gate_result_t result;

        if (lib_libcrypt == NULL)
        {
            static gate_string_t const libcrypt_name = GATE_STRING_INIT_STATIC("libcrypt.so");
            result = gate_library_open(&libcrypt_name, &lib_libcrypt, GATE_LIBRARY_FLAG_DEFAULT);
            if(GATE_FAILED(result))
            {
                return false;
            }
        }
        result = gate_library_get_function_name(lib_libcrypt, "crypt", &crypt_func);
        if(GATE_SUCCEEDED(result))
        {
            return crypt_func;
        }
        return NULL;
    }
}

gate_result_t cryptlib_hash(char const* passwd, gate_size_t passwd_length, gate_uint8_t* passhash, gate_size_t* ptr_passhash_len)
{
    gate_result_t ret;

    do
    {
        char input[GATE_PASSWORD_MAX_LENGTH];
        char setting[64];
        char salt_buffer[16];
        char const* ptr_setting;
        char* ptr_hash;
        gate_size_t hash_len;
        char* ptr_output = (char*)passhash;
        gate_size_t out_len = ptr_passhash_len ? *ptr_passhash_len : 0;
        gate_size_t out_used;
        gate_strbuilder_t builder;
        crypt_func_t crypt_func = load_libcrypt();

        if(crypt_func == NULL)
        {
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        if (!passwd || !passwd_length || !passhash || !ptr_passhash_len)
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        gate_str_print_text(input, sizeof(input), passwd, passwd_length);

        generate_salt(salt_buffer);

        gate_strbuilder_create_static(&builder, setting, sizeof(setting), 0);

        gate_strbuilder_append_cstr(&builder, "$5$");
        gate_strbuilder_append_text(&builder, salt_buffer, sizeof(salt_buffer));
        ptr_setting = gate_strbuilder_ptr(&builder, 0);

        /* NOTICE: crypt() uses a global buffer -> global lock */
        {
            ret = gate_platform_lock();
            GATE_BREAK_IF_FAILED(ret);

            ptr_hash = crypt_func(input, ptr_setting);
            hash_len = gate_str_length(ptr_hash);
            *ptr_passhash_len = gate_str_print_text(ptr_output, out_len, ptr_hash, hash_len);

            gate_platform_unlock();
        }

        ret = GATE_RESULT_OK;
    } while (0);
    
    return ret;
}

gate_result_t cryptlib_check(char const* passwd, gate_size_t passwd_length, gate_uint8_t const* passhash, gate_size_t passhash_len)
{
    gate_result_t ret;

    do
    {
        char input[GATE_PASSWORD_MAX_LENGTH];
        char setting[GATE_PASSWORD_MAX_LENGTH];
        gate_size_t setting_length;
        char output[GATE_PASSWORD_MAX_LENGTH];
        gate_size_t output_used;
        char const* ptr_hash;
        gate_size_t hash_len;
        crypt_func_t crypt_func = load_libcrypt();

        if(crypt_func == NULL)
        {
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        if (!passwd || !passwd_length || !passhash || !passhash_len)
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        gate_str_print_text(input, sizeof(input), passwd, passwd_length);
        setting_length = gate_str_print_text(setting, sizeof(setting), (char const*)passhash, passhash_len);

        /* NOTICE: crypt() uses a global buffer -> global lock */
        {
            ret = gate_platform_lock();
            GATE_BREAK_IF_FAILED(ret);

            ptr_hash = crypt_func(input, setting);
            hash_len = gate_str_length(ptr_hash);
            output_used = gate_str_print_text(output, sizeof(output), ptr_hash, hash_len);

            gate_platform_unlock();
        }

        if(gate_str_compare(setting, setting_length, output, output_used) == 0)
        {
            ret = GATE_RESULT_OK;
        }
        else
        {
            ret = GATE_RESULT_NOMATCH;
        }
    } while (0);
    
    return ret;
}

#endif /* GATE_ENCODE_CRYPT_IMPL */

static void pass_hash_sha256_salt(
    char const* passwd, gate_size_t passwd_length, 
    char const* salt, gate_size_t salt_length,
    gate_uint8_t* passhash, gate_size_t* ptr_passhash_len)
{
    char buffer[GATE_PASSWORD_MAX_LENGTH + 128];
    static gate_size_t const buffer_capacity = sizeof(buffer);
    static gate_size_t const rounds = 5000;
    gate_size_t ndx;
    gate_size_t hash_capacity = ptr_passhash_len ? *ptr_passhash_len : 0;

    gate_strbuilder_t builder;
    gate_string_t binstr;
    gate_sha256_t sha;
    gate_sha256_result_t sharesult;

    gate_sha256_init(&sha);

    for(ndx = 0; ndx != rounds; ++ndx)
    {
        gate_sha256_update(&sha, passwd, passwd_length);
        gate_sha256_update(&sha, salt, salt_length);
        gate_sha256_update(&sha, passwd, passwd_length);
        gate_sha256_finish(&sha, &sharesult);

        gate_sha256_init(&sha);
        gate_sha256_update(&sha, sharesult.hash, sizeof(sharesult.hash));
    }

    gate_strbuilder_create_static(&builder, (char*)passhash, hash_capacity, 0);
    gate_strbuilder_append_cstr(&builder, "$5$");
    gate_strbuilder_append_text(&builder, salt, salt_length);
    gate_strbuilder_append_cstr(&builder, "$");

    gate_string_create_static_len(&binstr, (char const*)&sharesult.hash[0], sizeof(sharesult.hash));

    gate_base64_encode(&binstr, &builder);
    *ptr_passhash_len = gate_strbuilder_length(&builder);
}

static gate_result_t pass_hash_sha256(char const* passwd, gate_size_t passwd_length, gate_uint8_t* passhash, gate_size_t* ptr_passhash_len)
{
    char salt[16];
    generate_salt(salt);
    pass_hash_sha256_salt(passwd, passwd_length, salt, sizeof(salt), passhash, ptr_passhash_len);
    return GATE_RESULT_OK;
}

gate_result_t pass_check_sha256(char const* passwd, gate_size_t passwd_length, gate_uint8_t const* passhash, gate_size_t passhash_len)
{
    gate_size_t pos;
    char const* ptr_salt;
    gate_size_t salt_len;
    gate_uint8_t test_hash[GATE_PASSWORD_MAX_HASH_LENGTH];
    gate_size_t test_hash_len = sizeof(test_hash);

    if (!gate_str_starts_with((char const*)passhash, passhash_len, "$5$", 3))
    {
        return GATE_RESULT_NOMATCH;
    }
    pos = gate_str_char_pos((char const*)passhash, passhash_len, '$', 3);
    if (GATE_STR_NPOS == pos)
    {
        return GATE_RESULT_NOMATCH;
    }
    ptr_salt = (char const*)(&passhash[3]);
    // "$5$salt$hash"
    salt_len = pos - 3;

    pass_hash_sha256_salt(passwd, passwd_length, ptr_salt, salt_len, test_hash, &test_hash_len);
    if (gate_str_compare((char const*)passhash, passhash_len, (char const*)test_hash, test_hash_len) != 0)
    {
        return GATE_RESULT_NOMATCH;
    }
    return GATE_RESULT_OK;
}



gate_result_t gate_password_hash(
    char const* passwd, gate_size_t passwd_length,
    gate_uint8_t* passhash, gate_size_t* ptr_passhash_len,
    gate_enumint_t flags)
{
#if defined(GATE_ENCODE_CRYPT_IMPL)
    if (GATE_FLAG_ENABLED(flags, GATE_PASSWORD_FLAG_SYSTEM))
    {
        return cryptlib_hash(passwd, passwd_length, passhash, ptr_passhash_len);
    }
#endif /* GATE_ENCODE_CRYPT_IMPL */

    return pass_hash_sha256(passwd, passwd_length, passhash, ptr_passhash_len);
}



gate_result_t gate_password_check(
    char const* passwd, gate_size_t passwd_length,
    gate_uint8_t const* passhash, gate_size_t passhash_len,
    gate_enumint_t flags)
{
#if defined(GATE_ENCODE_CRYPT_IMPL)
    if (GATE_FLAG_ENABLED(flags, GATE_PASSWORD_FLAG_SYSTEM))
    {
        return cryptlib_check(passwd, passwd_length, passhash, passhash_len);
    }
#endif /* GATE_ENCODE_CRYPT_IMPL */

    return pass_check_sha256(passwd, passwd_length, passhash, passhash_len);
}