450916
/* Test program to verify that RSA signing is thread-safe in OpenSSL. */
450916
450916
#include <assert.h>
450916
#include <errno.h>
450916
#include <fcntl.h>
450916
#include <limits.h>
450916
#include <pthread.h>
450916
#include <stdio.h>
450916
#include <string.h>
450916
#include <unistd.h>
450916
450916
#include <openssl/crypto.h>
450916
#include <openssl/err.h>
450916
#include <openssl/objects.h>
450916
#include <openssl/rand.h>
450916
#include <openssl/rsa.h>
450916
#include <openssl/md5.h>
450916
#include <openssl/ssl.h>
450916
450916
/* Just assume we want to do engine stuff if we're using 0.9.6b or
450916
 * higher. This assumption is only valid for versions bundled with RHL. */
450916
#if OPENSSL_VERSION_NUMBER  >= 0x0090602fL
450916
#include <openssl/engine.h>
450916
#define USE_ENGINE
450916
#endif
450916
450916
#define MAX_THREAD_COUNT	10000
450916
#define ITERATION_COUNT		10
450916
#define MAIN_COUNT		100
450916
450916
/* OpenSSL requires us to provide thread ID and locking primitives. */
450916
pthread_mutex_t *mutex_locks = NULL;
450916
static unsigned long
450916
thread_id_cb(void)
450916
{
450916
	return (unsigned long) pthread_self();
450916
}
450916
static void
450916
lock_cb(int mode, int n, const char *file, int line)
450916
{
450916
	if (mode & CRYPTO_LOCK) {
450916
		pthread_mutex_lock(&mutex_locks[n]);
450916
	} else {
450916
		pthread_mutex_unlock(&mutex_locks[n]);
450916
	}
450916
}
450916
450916
struct thread_args {
450916
	RSA *rsa;
450916
	int digest_type;
450916
	unsigned char *digest;
450916
	unsigned int digest_len;
450916
	unsigned char *signature;
450916
	unsigned int signature_len;
450916
	pthread_t main_thread;
450916
};
450916
450916
static int print = 0;
450916
450916
pthread_mutex_t sign_lock = PTHREAD_MUTEX_INITIALIZER;
450916
static int locked_sign = 0;
450916
static void SIGN_LOCK() {if (locked_sign) pthread_mutex_lock(&sign_lock);}
450916
static void SIGN_UNLOCK() {if (locked_sign) pthread_mutex_unlock(&sign_lock);}
450916
450916
pthread_mutex_t verify_lock = PTHREAD_MUTEX_INITIALIZER;
450916
static int locked_verify = 0;
450916
static void VERIFY_LOCK() {if (locked_verify) pthread_mutex_lock(&verify_lock);}
450916
static void VERIFY_UNLOCK() {if (locked_verify) pthread_mutex_unlock(&verify_lock);}
450916
450916
pthread_mutex_t failure_count_lock = PTHREAD_MUTEX_INITIALIZER;
450916
long failure_count = 0;
450916
static void
450916
failure()
450916
{
450916
	pthread_mutex_lock(&failure_count_lock);
450916
	failure_count++;
450916
	pthread_mutex_unlock(&failure_count_lock);
450916
}
450916
450916
static void *
450916
thread_main(void *argp)
450916
{
450916
	struct thread_args *args = argp;
450916
	unsigned char *signature;
450916
	unsigned int signature_len, signature_alloc_len;
450916
	int ret, i;
450916
450916
	signature_alloc_len = args->signature_len;
450916
	if (RSA_size(args->rsa) > signature_alloc_len) {
450916
		signature_alloc_len = RSA_size(args->rsa);
450916
	}
450916
	signature = malloc(signature_alloc_len);
450916
	if (signature == NULL) {
450916
		fprintf(stderr, "Skipping checks in thread %lu -- %s.\n",
450916
			(unsigned long) pthread_self(), strerror(errno));
450916
		pthread_exit(0);
450916
		return NULL;
450916
	}
450916
	for (i = 0; i < ITERATION_COUNT; i++) {
450916
		signature_len = signature_alloc_len;
450916
		SIGN_LOCK();
450916
		ret = RSA_check_key(args->rsa);
450916
		ERR_print_errors_fp(stdout);
450916
		if (ret != 1) {
450916
			failure();
450916
			break;
450916
		}
450916
		ret = RSA_sign(args->digest_type,
450916
			       args->digest,
450916
			       args->digest_len,
450916
			       signature, &signature_len,
450916
			       args->rsa);
450916
		SIGN_UNLOCK();
450916
		ERR_print_errors_fp(stdout);
450916
		if (ret != 1) {
450916
			failure();
450916
			break;
450916
		}
450916
450916
		VERIFY_LOCK();
450916
		ret = RSA_verify(args->digest_type,
450916
			         args->digest,
450916
			         args->digest_len,
450916
			         signature, signature_len,
450916
			         args->rsa);
450916
		VERIFY_UNLOCK();
450916
		if (ret != 1) {
450916
			fprintf(stderr,
450916
				"Signature from thread %lu(%d) fails "
450916
				"verification (passed in thread #%lu)!\n",
450916
				(long) pthread_self(), i,
450916
				(long) args->main_thread);
450916
			ERR_print_errors_fp(stdout);
450916
			failure();
450916
			continue;
450916
		}
450916
		if (print) {
450916
			fprintf(stderr, ">%d\n", i);
450916
		}
450916
	}
450916
	free(signature);
450916
450916
	pthread_exit(0);
450916
450916
	return NULL;
450916
}
450916
450916
unsigned char *
450916
xmemdup(unsigned char *s, size_t len)
450916
{
450916
	unsigned char *r;
450916
	r = malloc(len);
450916
	if (r == NULL) {
450916
		fprintf(stderr, "Out of memory.\n");
450916
		ERR_print_errors_fp(stdout);
450916
		assert(r != NULL);
450916
	}
450916
	memcpy(r, s, len);
450916
	return r;
450916
}
450916
450916
int
450916
main(int argc, char **argv)
450916
{
450916
	RSA *rsa;
450916
	MD5_CTX md5;
450916
	int fd, i;
450916
	pthread_t threads[MAX_THREAD_COUNT];
450916
	int thread_count = 1000;
450916
	unsigned char *message, *digest;
450916
	unsigned int message_len, digest_len;
450916
	unsigned char *correct_signature;
450916
	unsigned int correct_siglen, ret;
450916
	struct thread_args master_args, *args;
450916
	int sync = 0, seed = 0;
450916
	int again = 1;
450916
#ifdef USE_ENGINE
450916
	char *engine = NULL;
450916
	ENGINE *e = NULL;
450916
#endif
450916
450916
	pthread_mutex_init(&failure_count_lock, NULL);
450916
450916
	for (i = 1; i < argc; i++) {
450916
		if (strcmp(argv[i], "--seed") == 0) {
450916
			printf("Seeding PRNG.\n");
450916
			seed++;
450916
		} else
450916
		if (strcmp(argv[i], "--sync") == 0) {
450916
			printf("Running synchronized.\n");
450916
			sync++;
450916
		} else
450916
		if ((strcmp(argv[i], "--threads") == 0) && (i < argc - 1)) {
450916
			i++;
450916
			thread_count = atol(argv[i]);
450916
			if (thread_count > MAX_THREAD_COUNT) {
450916
				thread_count = MAX_THREAD_COUNT;
450916
			}
450916
			printf("Starting %d threads.\n", thread_count);
450916
			sync++;
450916
		} else
450916
		if (strcmp(argv[i], "--sign") == 0) {
450916
			printf("Locking signing.\n");
450916
			locked_sign++;
450916
		} else
450916
		if (strcmp(argv[i], "--verify") == 0) {
450916
			printf("Locking verifies.\n");
450916
			locked_verify++;
450916
		} else
450916
		if (strcmp(argv[i], "--print") == 0) {
450916
			printf("Tracing.\n");
450916
			print++;
450916
#ifdef USE_ENGINE
450916
		} else
450916
		if ((strcmp(argv[i], "--engine") == 0) && (i < argc - 1)) {
450916
			printf("Using engine \"%s\".\n", argv[i + 1]);
450916
			engine = argv[i + 1];
450916
			i++;
450916
#endif
450916
		} else {
450916
			printf("Bad argument: %s\n", argv[i]);
450916
			return 1;
450916
		}
450916
	}
450916
450916
	/* Get some random data to sign. */
450916
	fd = open("/dev/urandom", O_RDONLY);
450916
	if (fd == -1) {
450916
		fprintf(stderr, "Error opening /dev/urandom: %s\n",
450916
			strerror(errno));
450916
	}
450916
450916
	if (print) {
450916
		fprintf(stderr, "Reading random data.\n");
450916
	}
450916
	message = malloc(message_len = 9371);
450916
	read(fd, message, message_len);
450916
	close(fd);
450916
450916
	/* Initialize the SSL library and set up thread-safe locking. */
450916
	ERR_load_crypto_strings();
450916
	SSL_library_init();
450916
	mutex_locks = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
450916
	for (i = 0; i < CRYPTO_num_locks(); i++) {
450916
		pthread_mutex_init(&mutex_locks[i], NULL);
450916
	}
450916
	CRYPTO_set_id_callback(thread_id_cb);
450916
	CRYPTO_set_locking_callback(lock_cb);
450916
	ERR_print_errors_fp(stdout);
450916
450916
	/* Seed the PRNG if we were asked to do so. */
450916
	if (seed) {
450916
		if (print) {
450916
			fprintf(stderr, "Seeding PRNG.\n");
450916
		}
450916
		RAND_add(message, message_len, message_len);
450916
		ERR_print_errors_fp(stdout);
450916
	}
450916
450916
	/* Turn on a hardware crypto device if asked to do so. */
450916
#ifdef USE_ENGINE
450916
	if (engine) {
450916
#if OPENSSL_VERSION_NUMBER  >= 0x0090700fL
450916
		ENGINE_load_builtin_engines();
450916
#endif
450916
		if (print) {
450916
			fprintf(stderr, "Initializing \"%s\" engine.\n",
450916
				engine);
450916
		}
450916
		e = ENGINE_by_id(engine);
450916
		ERR_print_errors_fp(stdout);
450916
		if (e) {
450916
			i = ENGINE_init(e);
450916
			ERR_print_errors_fp(stdout);
450916
			i = ENGINE_set_default_RSA(e);
450916
			ERR_print_errors_fp(stdout);
450916
		}
450916
	}
450916
#endif
450916
450916
	/* Compute the digest for the signature. */
450916
	if (print) {
450916
		fprintf(stderr, "Computing digest.\n");
450916
	}
450916
	digest = malloc(digest_len = MD5_DIGEST_LENGTH);
450916
	MD5_Init(&md5;;
450916
	MD5_Update(&md5, message, message_len);
450916
	MD5_Final(digest, &md5;;
450916
450916
	/* Generate a signing key. */
450916
	if (print) {
450916
		fprintf(stderr, "Generating key.\n");
450916
	}
450916
	rsa = RSA_generate_key(4096, 3, NULL, NULL);
450916
	ERR_print_errors_fp(stdout);
450916
	if (rsa == NULL) {
450916
		_exit(1);
450916
	}
450916
450916
	/* Sign the data. */
450916
	correct_siglen = RSA_size(rsa);
450916
	correct_signature = malloc(correct_siglen);
450916
	for (i = 0; i < MAIN_COUNT; i++) {
450916
		if (print) {
450916
			fprintf(stderr, "Signing data (%d).\n", i);
450916
		}
450916
		ret = RSA_check_key(rsa);
450916
		ERR_print_errors_fp(stdout);
450916
		if (ret != 1) {
450916
			failure();
450916
		}
450916
		correct_siglen = RSA_size(rsa);
450916
		ret = RSA_sign(NID_md5, digest, digest_len,
450916
			       correct_signature, &correct_siglen,
450916
			       rsa);
450916
		ERR_print_errors_fp(stdout);
450916
		if (ret != 1) {
450916
			_exit(2);
450916
		}
450916
		if (print) {
450916
			fprintf(stderr, "Verifying data (%d).\n", i);
450916
		}
450916
		ret = RSA_verify(NID_md5, digest, digest_len,
450916
			         correct_signature, correct_siglen,
450916
			         rsa);
450916
		if (ret != 1) {
450916
			_exit(2);
450916
		}
450916
	}
450916
450916
	/* Collect up the inforamtion which other threads will need for
450916
	 * comparing their signature results with ours. */
450916
	master_args.rsa = rsa;
450916
	master_args.digest_type = NID_md5;
450916
	master_args.digest = digest;
450916
	master_args.digest_len = digest_len;
450916
	master_args.signature = correct_signature;
450916
	master_args.signature_len = correct_siglen;
450916
	master_args.main_thread = pthread_self();
450916
	
450916
	fprintf(stdout, "Performing %d signatures in each of %d threads "
450916
		"(%d, %d).\n", ITERATION_COUNT, thread_count,
450916
		digest_len, correct_siglen);
450916
	fflush(NULL);
450916
450916
	/* Start up all of the threads. */
450916
	for (i = 0; i < thread_count; i++) {
450916
		args = malloc(sizeof(struct thread_args));
450916
		args->rsa = RSAPrivateKey_dup(master_args.rsa);
450916
		args->digest_type = master_args.digest_type;
450916
		args->digest_len = master_args.digest_len;
450916
		args->digest = xmemdup(master_args.digest, args->digest_len);
450916
		args->signature_len = master_args.signature_len;
450916
		args->signature = xmemdup(master_args.signature,
450916
					  args->signature_len);
450916
		args->main_thread = pthread_self();
450916
		ret = pthread_create(&threads[i], NULL, thread_main, args);
450916
		while ((ret != 0) && (errno == EAGAIN)) {
450916
			ret = pthread_create(&threads[i], NULL,
450916
					     thread_main, &args);
450916
			fprintf(stderr, "Thread limit hit at %d.\n", i);
450916
		}
450916
		if (ret != 0) {
450916
			fprintf(stderr, "Unable to create thread %d: %s.\n",
450916
				i, strerror(errno));
450916
			threads[i] = -1;
450916
		} else {
450916
			if (sync) {
450916
				ret = pthread_join(threads[i], NULL);
450916
				assert(ret == 0);
450916
			}
450916
			if (print) {
450916
				fprintf(stderr, "%d\n", i);
450916
			}
450916
		}
450916
	}
450916
450916
	/* Wait for all threads to complete.  So long as we can find an
450916
	 * unjoined thread, keep joining threads. */
450916
	do {
450916
		again = 0;
450916
		for (i = 0; i < thread_count; i++) {
450916
			/* If we have an unterminated thread, join it. */
450916
			if (threads[i] != -1) {
450916
				again = 1;
450916
				if (print) {
450916
					fprintf(stderr, "Joining thread %d.\n",
450916
						i);
450916
				}
450916
				pthread_join(threads[i], NULL);
450916
				threads[i] = -1;
450916
				break;
450916
			}
450916
		}
450916
	} while (again == 1);
450916
450916
	fprintf(stderr, "%ld failures\n", failure_count);
450916
450916
	return (failure_count != 0);
450916
}