1 /*
2  * Copyright (C) 2001-2016 Free Software Foundation, Inc.
3  * Copyright (C) 2015-2016 Red Hat, Inc.
4  *
5  * Author: Nikos Mavrogiannopoulos
6  *
7  * This file is part of GnuTLS.
8  *
9  * The GnuTLS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
21  *
22  */
23 
24 #include "gnutls_int.h"
25 #include "errors.h"
26 #include <libtasn1.h>
27 #include <dh.h>
28 #include <random.h>
29 #include <gnutls/pkcs11.h>
30 
31 #include <hello_ext.h>	/* for _gnutls_hello_ext_init */
32 #include <supplemental.h> /* for _gnutls_supplemental_deinit */
33 #include <locks.h>
34 #include <system.h>
35 #include <accelerated/cryptodev.h>
36 #include <accelerated/accelerated.h>
37 #include <fips.h>
38 #include <atfork.h>
39 #include <system-keys.h>
40 #include "str.h"
41 #include "global.h"
42 
43 /* Minimum library versions we accept. */
44 #define GNUTLS_MIN_LIBTASN1_VERSION "0.3.4"
45 
46 #ifdef __sun
47 # pragma fini(lib_deinit)
48 # pragma init(lib_init)
49 # define _CONSTRUCTOR
50 # define _DESTRUCTOR
51 #else
52 # define _CONSTRUCTOR __attribute__((constructor))
53 # define _DESTRUCTOR __attribute__((destructor))
54 #endif
55 
56 #ifndef _WIN32
57 int __attribute__((weak)) _gnutls_global_init_skip(void);
_gnutls_global_init_skip(void)58 int _gnutls_global_init_skip(void)
59 {
60 	return 0;
61 }
62 #else
_gnutls_global_init_skip(void)63 inline static int _gnutls_global_init_skip(void)
64 {
65 	return 0;
66 }
67 #endif
68 
69 /* created by asn1c */
70 extern const ASN1_ARRAY_TYPE gnutls_asn1_tab[];
71 extern const ASN1_ARRAY_TYPE pkix_asn1_tab[];
72 void *_gnutls_file_mutex;
73 void *_gnutls_pkcs11_mutex;
74 
75 ASN1_TYPE _gnutls_pkix1_asn = ASN1_TYPE_EMPTY;
76 ASN1_TYPE _gnutls_gnutls_asn = ASN1_TYPE_EMPTY;
77 
78 gnutls_log_func _gnutls_log_func = NULL;
79 gnutls_audit_log_func _gnutls_audit_log_func = NULL;
80 int _gnutls_log_level = 0;	/* default log level */
81 
82 unsigned int _gnutls_global_version = GNUTLS_VERSION_NUMBER;
83 
84 static int _gnutls_global_init(unsigned constructor);
85 static void _gnutls_global_deinit(unsigned destructor);
86 
default_log_func(int level,const char * str)87 static void default_log_func(int level, const char* str)
88 {
89 	fprintf(stderr, "gnutls[%d]: %s", level, str);
90 }
91 
92 /**
93  * gnutls_global_set_log_function:
94  * @log_func: it's a log function
95  *
96  * This is the function where you set the logging function gnutls is
97  * going to use.  This function only accepts a character array.
98  * Normally you may not use this function since it is only used for
99  * debugging purposes.
100  *
101  * @gnutls_log_func is of the form,
102  * void (*gnutls_log_func)( int level, const char*);
103  **/
gnutls_global_set_log_function(gnutls_log_func log_func)104 void gnutls_global_set_log_function(gnutls_log_func log_func)
105 {
106 	_gnutls_log_func = log_func;
107 }
108 
109 /**
110  * gnutls_global_set_audit_log_function:
111  * @log_func: it is the audit log function
112  *
113  * This is the function to set the audit logging function. This
114  * is a function to report important issues, such as possible
115  * attacks in the protocol. This is different from gnutls_global_set_log_function()
116  * because it will report also session-specific events. The session
117  * parameter will be null if there is no corresponding TLS session.
118  *
119  * @gnutls_audit_log_func is of the form,
120  * void (*gnutls_audit_log_func)( gnutls_session_t, const char*);
121  *
122  * Since: 3.0
123  **/
gnutls_global_set_audit_log_function(gnutls_audit_log_func log_func)124 void gnutls_global_set_audit_log_function(gnutls_audit_log_func log_func)
125 {
126 	_gnutls_audit_log_func = log_func;
127 }
128 
129 /**
130  * gnutls_global_set_time_function:
131  * @time_func: it's the system time function, a gnutls_time_func() callback.
132  *
133  * This is the function where you can override the default system time
134  * function.  The application provided function should behave the same
135  * as the standard function.
136  *
137  * Since: 2.12.0
138  **/
gnutls_global_set_time_function(gnutls_time_func time_func)139 void gnutls_global_set_time_function(gnutls_time_func time_func)
140 {
141 	gnutls_time = time_func;
142 }
143 
144 /**
145  * gnutls_global_set_log_level:
146  * @level: it's an integer from 0 to 99.
147  *
148  * This is the function that allows you to set the log level.  The
149  * level is an integer between 0 and 9.  Higher values mean more
150  * verbosity. The default value is 0.  Larger values should only be
151  * used with care, since they may reveal sensitive information.
152  *
153  * Use a log level over 10 to enable all debugging options.
154  **/
gnutls_global_set_log_level(int level)155 void gnutls_global_set_log_level(int level)
156 {
157 	_gnutls_log_level = level;
158 }
159 
160 /**
161  * gnutls_global_set_mem_functions:
162  * @alloc_func: it's the default memory allocation function. Like malloc().
163  * @secure_alloc_func: This is the memory allocation function that will be used for sensitive data.
164  * @is_secure_func: a function that returns 0 if the memory given is not secure. May be NULL.
165  * @realloc_func: A realloc function
166  * @free_func: The function that frees allocated data. Must accept a NULL pointer.
167  *
168  * Deprecated: since 3.3.0 it is no longer possible to replace the internally used
169  *  memory allocation functions
170  *
171  * This is the function where you set the memory allocation functions
172  * gnutls is going to use. By default the libc's allocation functions
173  * (malloc(), free()), are used by gnutls, to allocate both sensitive
174  * and not sensitive data.  This function is provided to set the
175  * memory allocation functions to something other than the defaults
176  *
177  * This function must be called before gnutls_global_init() is called.
178  * This function is not thread safe.
179  **/
180 void
gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func,gnutls_alloc_function secure_alloc_func,gnutls_is_secure_function is_secure_func,gnutls_realloc_function realloc_func,gnutls_free_function free_func)181 gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func,
182 				gnutls_alloc_function secure_alloc_func,
183 				gnutls_is_secure_function is_secure_func,
184 				gnutls_realloc_function realloc_func,
185 				gnutls_free_function free_func)
186 {
187 	_gnutls_debug_log("called the deprecated gnutls_global_set_mem_functions()\n");
188 }
189 
190 GNUTLS_STATIC_MUTEX(global_init_mutex);
191 static int _gnutls_init = 0;
192 
193 /* cache the return code */
194 static int _gnutls_init_ret = 0;
195 
196 /**
197  * gnutls_global_init:
198  *
199  * Since GnuTLS 3.3.0 this function is no longer necessary to be explicitly
200  * called. To disable the implicit call (in a library constructor) of this
201  * function set the environment variable %GNUTLS_NO_EXPLICIT_INIT to 1.
202  *
203  * This function performs any required precalculations, detects
204  * the supported CPU capabilities and initializes the underlying
205  * cryptographic backend. In order to free any resources
206  * taken by this call you should gnutls_global_deinit()
207  * when gnutls usage is no longer needed.
208  *
209  * This function increments a global counter, so that
210  * gnutls_global_deinit() only releases resources when it has been
211  * called as many times as gnutls_global_init().  This is useful when
212  * GnuTLS is used by more than one library in an application.  This
213  * function can be called many times, but will only do something the
214  * first time. It is thread safe since GnuTLS 3.3.0.
215  *
216  * A subsequent call of this function if the initial has failed will
217  * return the same error code.
218  *
219  * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned,
220  *   otherwise a negative error code is returned.
221  **/
gnutls_global_init(void)222 int gnutls_global_init(void)
223 {
224 	return _gnutls_global_init(0);
225 }
226 
_gnutls_global_init(unsigned constructor)227 static int _gnutls_global_init(unsigned constructor)
228 {
229 	int ret = 0, res;
230 	int level;
231 	const char* e;
232 
233 	if (!constructor) {
234 		GNUTLS_STATIC_MUTEX_LOCK(global_init_mutex);
235 	}
236 
237 	_gnutls_init++;
238 	if (_gnutls_init > 1) {
239 		if (_gnutls_init == 2 && _gnutls_init_ret == 0) {
240 			/* some applications may close the urandom fd
241 			 * before calling gnutls_global_init(). in that
242 			 * case reopen it */
243 			ret = _gnutls_rnd_check();
244 			if (ret < 0) {
245 				gnutls_assert();
246 				goto out;
247 			}
248 		}
249 		ret = _gnutls_init_ret;
250 		goto out;
251 	}
252 
253 	_gnutls_switch_lib_state(LIB_STATE_INIT);
254 
255 	e = secure_getenv("GNUTLS_DEBUG_LEVEL");
256 	if (e != NULL) {
257 		level = atoi(e);
258 		gnutls_global_set_log_level(level);
259 		if (_gnutls_log_func == NULL)
260 			gnutls_global_set_log_function(default_log_func);
261 		_gnutls_debug_log("Enabled GnuTLS "VERSION" logging...\n");
262 	}
263 
264 #ifdef HAVE_DCGETTEXT
265 	bindtextdomain(PACKAGE, LOCALEDIR);
266 #endif
267 
268 	res = gnutls_crypto_init();
269 	if (res != 0) {
270 		gnutls_assert();
271 		ret = GNUTLS_E_CRYPTO_INIT_FAILED;
272 		goto out;
273 	}
274 
275 	ret = _gnutls_system_key_init();
276 	if (ret != 0) {
277 		gnutls_assert();
278 	}
279 
280 	/* initialize ASN.1 parser
281 	 */
282 	if (asn1_check_version(GNUTLS_MIN_LIBTASN1_VERSION) == NULL) {
283 		gnutls_assert();
284 		_gnutls_debug_log
285 		    ("Checking for libtasn1 failed: %s < %s\n",
286 		     asn1_check_version(NULL),
287 		     GNUTLS_MIN_LIBTASN1_VERSION);
288 		ret = GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY;
289 		goto out;
290 	}
291 
292 	_gnutls_pkix1_asn = ASN1_TYPE_EMPTY;
293 	res = asn1_array2tree(pkix_asn1_tab, &_gnutls_pkix1_asn, NULL);
294 	if (res != ASN1_SUCCESS) {
295 		gnutls_assert();
296 		ret = _gnutls_asn2err(res);
297 		goto out;
298 	}
299 
300 	res = asn1_array2tree(gnutls_asn1_tab, &_gnutls_gnutls_asn, NULL);
301 	if (res != ASN1_SUCCESS) {
302 		gnutls_assert();
303 		ret = _gnutls_asn2err(res);
304 		goto out;
305 	}
306 
307 	/* Initialize the random generator */
308 	ret = _gnutls_rnd_preinit();
309 	if (ret < 0) {
310 		gnutls_assert();
311 		goto out;
312 	}
313 
314 	/* Initialize the default TLS extensions */
315 	ret = _gnutls_hello_ext_init();
316 	if (ret < 0) {
317 		gnutls_assert();
318 		goto out;
319 	}
320 
321 	ret = gnutls_mutex_init(&_gnutls_file_mutex);
322 	if (ret < 0) {
323 		gnutls_assert();
324 		goto out;
325 	}
326 
327 	ret = gnutls_mutex_init(&_gnutls_pkcs11_mutex);
328 	if (ret < 0) {
329 		gnutls_assert();
330 		goto out;
331 	}
332 
333 	ret = gnutls_system_global_init();
334 	if (ret < 0) {
335 		gnutls_assert();
336 		goto out;
337 	}
338 
339 #ifndef _WIN32
340 	ret = _gnutls_register_fork_handler();
341 	if (ret < 0) {
342 		gnutls_assert();
343 		goto out;
344 	}
345 #endif
346 
347 #ifdef ENABLE_FIPS140
348 	res = _gnutls_fips_mode_enabled();
349 	/* res == 1 -> fips140-2 mode enabled
350 	 * res == 2 -> only self checks performed - but no failure
351 	 * res == not in fips140 mode
352 	 */
353 	if (res != 0) {
354 		_gnutls_debug_log("FIPS140-2 mode: %d\n", res);
355 		_gnutls_priority_update_fips();
356 
357 		/* first round of self checks, these are done on the
358 		 * nettle algorithms which are used internally */
359 		ret = _gnutls_fips_perform_self_checks1();
360 		if (res != 2) {
361 			if (ret < 0) {
362 				gnutls_assert();
363 				goto out;
364 			}
365 		}
366 	}
367 #endif
368 
369 	_gnutls_register_accel_crypto();
370 	_gnutls_cryptodev_init();
371 
372 #ifdef ENABLE_FIPS140
373 	/* These self tests are performed on the overridden algorithms
374 	 * (e.g., AESNI overridden AES). They are after _gnutls_register_accel_crypto()
375 	 * intentionally */
376 	if (res != 0) {
377 		ret = _gnutls_fips_perform_self_checks2();
378 		if (res != 2) {
379 			if (ret < 0) {
380 				gnutls_assert();
381 				goto out;
382 			}
383 		}
384 		_gnutls_fips_mode_reset_zombie();
385 	}
386 #endif
387 	_gnutls_load_system_priorities();
388 	_gnutls_switch_lib_state(LIB_STATE_OPERATIONAL);
389 	ret = 0;
390 
391       out:
392 	_gnutls_init_ret = ret;
393 	if (!constructor) {
394 		GNUTLS_STATIC_MUTEX_UNLOCK(global_init_mutex);
395 	}
396 	return ret;
397 }
398 
_gnutls_global_deinit(unsigned destructor)399 static void _gnutls_global_deinit(unsigned destructor)
400 {
401 	if (!destructor) {
402 		GNUTLS_STATIC_MUTEX_LOCK(global_init_mutex);
403 	}
404 
405 	if (_gnutls_init == 1) {
406 		_gnutls_init = 0;
407 		if (_gnutls_init_ret < 0) {
408 			/* only deinitialize if gnutls_global_init() has
409 			 * succeeded */
410 			gnutls_assert();
411 			goto fail;
412 		}
413 
414 		_gnutls_system_key_deinit();
415 		gnutls_crypto_deinit();
416 		_gnutls_rnd_deinit();
417 		_gnutls_hello_ext_deinit();
418 		asn1_delete_structure(&_gnutls_gnutls_asn);
419 		asn1_delete_structure(&_gnutls_pkix1_asn);
420 
421 		_gnutls_crypto_deregister();
422 		gnutls_system_global_deinit();
423 		_gnutls_cryptodev_deinit();
424 
425 		_gnutls_supplemental_deinit();
426 		_gnutls_unload_system_priorities();
427 
428 #ifdef ENABLE_PKCS11
429 		/* Do not try to deinitialize the PKCS #11 libraries
430 		 * from the destructor. If we do and the PKCS #11 modules
431 		 * are already being unloaded, we may crash.
432 		 */
433 		if (destructor == 0) {
434 			gnutls_pkcs11_deinit();
435 		}
436 #endif
437 #ifdef HAVE_TROUSERS
438 		_gnutls_tpm_global_deinit();
439 #endif
440 
441 		_gnutls_nss_keylog_deinit();
442 
443 		gnutls_mutex_deinit(&_gnutls_file_mutex);
444 		gnutls_mutex_deinit(&_gnutls_pkcs11_mutex);
445 	} else {
446 		if (_gnutls_init > 0)
447 			_gnutls_init--;
448 	}
449 
450  fail:
451 	if (!destructor) {
452 		GNUTLS_STATIC_MUTEX_UNLOCK(global_init_mutex);
453 	}
454 }
455 
456 /**
457  * gnutls_global_deinit:
458  *
459  * This function deinitializes the global data, that were initialized
460  * using gnutls_global_init().
461  *
462  * Since GnuTLS 3.3.0 this function is no longer necessary to be explicitly
463  * called. GnuTLS will automatically deinitialize on library destructor. See
464  * gnutls_global_init() for disabling the implicit initialization/deinitialization.
465  *
466  **/
gnutls_global_deinit(void)467 void gnutls_global_deinit(void)
468 {
469 	_gnutls_global_deinit(0);
470 }
471 
472 /**
473  * gnutls_check_version:
474  * @req_version: version string to compare with, or %NULL.
475  *
476  * Check the GnuTLS Library version against the provided string.
477  * See %GNUTLS_VERSION for a suitable @req_version string.
478  *
479  * See also gnutls_check_version_numeric(), which provides this
480  * functionality as a macro.
481  *
482  * Returns: Check that the version of the library is at
483  *   minimum the one given as a string in @req_version and return the
484  *   actual version string of the library; return %NULL if the
485  *   condition is not met.  If %NULL is passed to this function no
486  *   check is done and only the version string is returned.
487   **/
gnutls_check_version(const char * req_version)488 const char *gnutls_check_version(const char *req_version)
489 {
490 	if (!req_version || strverscmp(req_version, VERSION) <= 0)
491 		return VERSION;
492 
493 	return NULL;
494 }
495 
lib_init(void)496 static void _CONSTRUCTOR lib_init(void)
497 {
498 int ret;
499 const char *e;
500 
501 	if (_gnutls_global_init_skip() != 0)
502 		return;
503 
504 	e = secure_getenv("GNUTLS_NO_EXPLICIT_INIT");
505 	if (e != NULL) {
506 		ret = atoi(e);
507 		if (ret == 1)
508 			return;
509 	}
510 
511 	ret = _gnutls_global_init(1);
512 	if (ret < 0) {
513 		fprintf(stderr, "Error in GnuTLS initialization: %s\n", gnutls_strerror(ret));
514 		_gnutls_switch_lib_state(LIB_STATE_ERROR);
515 	}
516 }
517 
lib_deinit(void)518 static void _DESTRUCTOR lib_deinit(void)
519 {
520 	const char *e;
521 
522 	if (_gnutls_global_init_skip() != 0)
523 		return;
524 
525 	e = secure_getenv("GNUTLS_NO_EXPLICIT_INIT");
526 	if (e != NULL) {
527 		int ret = atoi(e);
528 		if (ret == 1)
529 			return;
530 	}
531 
532 	_gnutls_global_deinit(1);
533 }
534