summaryrefslogtreecommitdiff
path: root/src/crypto.c
blob: 10d313c96e8f13199c53bc709af97c64d826e34c (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
/*
 *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Contact: Krzysztof Jackiewicz <k.jackiewicz@samsung.com>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */

/**
 * @file crypto.c
 * @brief
 */

#define _GNU_SOURCE
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/random.h>

#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/rand.h>

#include <yaca_crypto.h>
#include <yaca_error.h>

#include "internal.h"

#if OPENSSL_VERSION_NUMBER < 0x10100000L
static pthread_mutex_t *mutexes = NULL;
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */

static __thread bool current_thread_initialized = false;
static size_t threads_cnt = 0;
static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
static const RAND_METHOD *saved_rand_method = NULL;
#ifndef SYS_getrandom
static int urandom_fd = -2;
#endif  /* SYS_getrandom */

static int getrandom_wrapper(unsigned char *buf, int num)
{
	size_t received = 0;
	size_t remaining = num;

#ifndef SYS_getrandom
	if (urandom_fd == -2)
		return 0;
#endif /* SYS_getrandom */

	while (remaining > 0) {
#ifdef SYS_getrandom
		ssize_t n = syscall(SYS_getrandom, buf + received, remaining, 0);
#else /* SYS_getrandom */
		ssize_t n = read(urandom_fd, buf + received, remaining);
#endif /* SYS_getrandom */

		if (n == -1) {
			if (errno == EINTR)
				continue;

			return 0;
		}

		received += n;
		remaining -= n;
	}

	return 1;
}

#if OPENSSL_VERSION_NUMBER >= 0x10100000L

static int RAND_METHOD_seed(UNUSED const void *buf, UNUSED int num)
{
	return 1;
}

static int RAND_METHOD_add(UNUSED const void *buf, UNUSED int num, UNUSED double entropy)
{
	return 1;
}

#else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */

static void RAND_METHOD_seed(UNUSED const void *buf, UNUSED int num)
{
}

static void RAND_METHOD_add(UNUSED const void *buf, UNUSED int num, UNUSED double entropy)
{
}

#endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */

static int RAND_METHOD_bytes(unsigned char *buf, int num)
{
	return getrandom_wrapper(buf, num);
}

static void RAND_METHOD_cleanup(void)
{
}

static int RAND_METHOD_pseudorand(UNUSED unsigned char *buf, UNUSED int num)
{
	return getrandom_wrapper(buf, num);
}

static int RAND_METHOD_status(void)
{
#ifdef SYS_getrandom
	char tmp;
	int n = syscall(SYS_getrandom, &tmp, 1, GRND_NONBLOCK);
	if (n == -1 && errno == EAGAIN)
		return 0;
#endif /* SYS_getrandom */

	return 1;
}

static const RAND_METHOD new_rand_method = {
	RAND_METHOD_seed,
	RAND_METHOD_bytes,
	RAND_METHOD_cleanup,
	RAND_METHOD_add,
	RAND_METHOD_pseudorand,
	RAND_METHOD_status,
};

#if OPENSSL_VERSION_NUMBER < 0x10100000L

static void locking_callback(int mode, int type, UNUSED const char *file, UNUSED int line)
{
	/* Ignore NULL mutexes and lock/unlock error codes as we can't do anything
	 * about them. */

	if (mutexes == NULL)
		return;

	if (mode & CRYPTO_LOCK)
		pthread_mutex_lock(&mutexes[type]);
	else if (mode & CRYPTO_UNLOCK)
		pthread_mutex_unlock(&mutexes[type]);
}

static unsigned long thread_id_callback()
{
	return pthread_self();
}

static void destroy_mutexes(int count)
{
	if (mutexes != NULL) {
		for (int i = 0; i < count; i++) {
			/* Ignore returned value as we can't do anything about it */
			pthread_mutex_destroy(&mutexes[i]);
		}
		yaca_free(mutexes);
		mutexes = NULL;
	}
}

#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */

API int yaca_initialize(void)
{
	int ret = YACA_ERROR_NONE;

	/* no calling yaca_initialize() twice on the same thread */
	if (current_thread_initialized)
		return YACA_ERROR_INTERNAL;

	pthread_mutex_lock(&init_mutex);
	{
		if (threads_cnt == 0) {

#ifndef SYS_getrandom
			if (urandom_fd == -2) {
				int fd;

				do {
					fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
				} while (fd == -1 && errno == EINTR);

				if (fd < 0) {
					ret = YACA_ERROR_INTERNAL;
					goto exit;
				}

				urandom_fd = fd;
			}
#endif /* SYS_getrandom */

			OPENSSL_init();

			/* Use getrandom from urandom pool by default.
			 * As per the following:
			 * http://www.2uo.de/myths-about-urandom/
			 * http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
			 *
			 * OpenSSL's PRNG has issues:
			 * https://eprint.iacr.org/2016/367.pdf

			 * Some other things to check/consider for the future:
			 * - entropy on a mobile device (no mouse/keyboard)
			 * - hardware random generator (RdRand on new Intels, Samsung hardware?)
			 */
			saved_rand_method = RAND_get_rand_method();
			RAND_set_rand_method(&new_rand_method);

			OpenSSL_add_all_digests();
			OpenSSL_add_all_ciphers();

#if OPENSSL_VERSION_NUMBER < 0x10100000L
			/* enable threads support */
			assert(mutexes == NULL);

			if (CRYPTO_num_locks() > 0) {
				ret = yaca_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t),
								  (void**)&mutexes);

				if (ret != YACA_ERROR_NONE)
					goto exit;

				for (int i = 0; i < CRYPTO_num_locks(); i++) {
					if (pthread_mutex_init(&mutexes[i], NULL) != 0) {
						ret = YACA_ERROR_NONE;
						switch (errno) {
						case ENOMEM:
							ret = YACA_ERROR_OUT_OF_MEMORY;
							break;
						case EAGAIN:
						case EPERM:
						case EBUSY:
						case EINVAL:
						default:
							ret = YACA_ERROR_INTERNAL;
						}
						destroy_mutexes(i);

						goto exit;
					}
				}

				CRYPTO_set_id_callback(thread_id_callback);
				CRYPTO_set_locking_callback(locking_callback);
			}
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */

			/*
			 * TODO:
			 * - We should also decide on OpenSSL config.
			 * - Here's a good tutorial for initialization and cleanup:
			 *   https://wiki.openssl.org/index.php/Library_Initialization
			 */
		}
		threads_cnt++;
		current_thread_initialized = true;
	}

#if OPENSSL_VERSION_NUMBER < 0x10100000L || !defined SYS_getrandom
exit:
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L || !defined SYS_getrandom */

	pthread_mutex_unlock(&init_mutex);

	return ret;
}

API void yaca_cleanup(void)
{
	/* calling cleanup twice on the same thread is a NOP */
	if (!current_thread_initialized)
		return;

	/* per thread cleanup */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	ERR_remove_thread_state(NULL);
#endif  /* OPENSSL_VERSION_NUMBER < 0x10100000L */
	CRYPTO_cleanup_all_ex_data();

	pthread_mutex_lock(&init_mutex);
	{
		/* last one turns off the light */
		if (threads_cnt == 1) {
			ERR_free_strings();
			EVP_cleanup();
			RAND_cleanup();
			RAND_set_rand_method(saved_rand_method);

#ifndef SYS_getrandom
			close(urandom_fd);
			urandom_fd = -2;
#endif /* SYS_getrandom */

#if OPENSSL_VERSION_NUMBER < 0x10100000L
			/* threads support cleanup */
			CRYPTO_set_id_callback(NULL);
			CRYPTO_set_locking_callback(NULL);

			destroy_mutexes(CRYPTO_num_locks());
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
		}

		assert(threads_cnt > 0);

		threads_cnt--;
		current_thread_initialized = false;
	}
	pthread_mutex_unlock(&init_mutex);
}

API int yaca_malloc(size_t size, void **memory)
{
	if (size == 0 || memory == NULL)
		return YACA_ERROR_INVALID_PARAMETER;

	*memory = OPENSSL_malloc(size);
	if (*memory == NULL) {
		ERROR_DUMP(YACA_ERROR_OUT_OF_MEMORY);
		return YACA_ERROR_OUT_OF_MEMORY;
	}

	return YACA_ERROR_NONE;
}

API int yaca_zalloc(size_t size, void **memory)
{
	int ret = yaca_malloc(size, memory);
	if (ret != YACA_ERROR_NONE)
		return ret;

	memset(*memory, 0, size);

	return YACA_ERROR_NONE;
}

API int yaca_realloc(size_t size, void **memory)
{
	if (size == 0 || memory == NULL)
		return YACA_ERROR_INVALID_PARAMETER;

	void *tmp = OPENSSL_realloc(*memory, size);
	if (tmp == NULL) {
		ERROR_DUMP(YACA_ERROR_OUT_OF_MEMORY);
		return YACA_ERROR_OUT_OF_MEMORY;
	}

	*memory = tmp;

	return YACA_ERROR_NONE;
}

API void yaca_free(void *memory)
{
	OPENSSL_free(memory);
}

API int yaca_randomize_bytes(char *data, size_t data_len)
{
	int ret;

	if (data == NULL || data_len == 0)
		return YACA_ERROR_INVALID_PARAMETER;

	ret = RAND_bytes((unsigned char *)data, data_len);
	if (ret != 1) {
		ret = YACA_ERROR_INTERNAL;
		ERROR_DUMP(ret);
		return ret;
	}

	return YACA_ERROR_NONE;
}

API int yaca_context_set_property(yaca_context_h ctx, yaca_property_e property,
								  const void *value, size_t value_len)
{
	if (ctx == YACA_CONTEXT_NULL || ctx->set_property == NULL)
		return YACA_ERROR_INVALID_PARAMETER;

	return ctx->set_property(ctx, property, value, value_len);
}

API int yaca_context_get_property(const yaca_context_h ctx, yaca_property_e property,
								  void **value, size_t *value_len)
{
	if (ctx == YACA_CONTEXT_NULL || ctx->get_property == NULL)
		return YACA_ERROR_INVALID_PARAMETER;

	return ctx->get_property(ctx, property, value, value_len);
}

API void yaca_context_destroy(yaca_context_h ctx)
{
	if (ctx != YACA_CONTEXT_NULL) {
		assert(ctx->context_destroy != NULL);
		ctx->context_destroy(ctx);
		yaca_free(ctx);
	}
}

API int yaca_context_get_output_length(const yaca_context_h ctx,
									   size_t input_len, size_t *output_len)
{
	if (ctx == YACA_CONTEXT_NULL || output_len == NULL ||
		ctx->get_output_length == NULL)
		return YACA_ERROR_INVALID_PARAMETER;

	return ctx->get_output_length(ctx, input_len, output_len);
}

API int yaca_memcmp(const void *first, const void *second, size_t len)
{
	if (CRYPTO_memcmp(first, second, len) == 0)
		return YACA_ERROR_NONE;

	return YACA_ERROR_DATA_MISMATCH;
}