#32609·openssl

TSAN: race condition in `X509_self_signed`

Author: aydinmercanCreated Aug 31, 2026Updated Sep 29, 2026
Labelsbranch: masterapproval: review pendingtriaged: bug

A race condition occurs when multiple threads call X509_self_signed on a certificate without cached data.

The story is as follows:

  • Multiple threads call X509_self_signed
  • Inside ossl_x509v3_cache_extensions, both threads get the read lock and decide that the cert has not been processed.
  • One of them gets the write lock and sets the cached fields as normal
  • The write lock is released, and is gained by another thread.
  • The second thread will write the cached fields again while the first thread checks for the EXFLAG_SS flag inside cert->ex_flags.

The written flags will be the same as the existing value but it shouldn't be relied on (plus it trips up TSAN)

The problem has existed since [792a760ac2e7ab64d7ff4597e48bb94e2520dfdb] and has been found when trying to use OpenSSL >=4 inside the BIND9 CI.

Here is a stupid/simple reproducer:

#define _GNU_SOURCE

#include <pthread.h>
#include <stdio.h>

#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>

static X509 *_x509 = NULL;

static pthread_barrier_t _barrier;

__attribute__((optnone, noinline)) static void *
work(void *arg __attribute__((unused))) {
	pthread_barrier_wait(&_barrier);

	return (void *)(uintptr_t)X509_self_signed(_x509, 0);
}

int
main(void) {
	OPENSSL_init_ssl(0, NULL);

	EVP_PKEY *pkey = EVP_EC_gen("P-256");

	_x509 = X509_new();

	X509_set_version(_x509, 2);
	ASN1_INTEGER_set(X509_get_serialNumber(_x509), 1234L);
	X509_gmtime_adj(X509_getm_notBefore(_x509), -300);
	X509_gmtime_adj(X509_getm_notAfter(_x509), 300000);

	X509_NAME *name = X509_NAME_new();
	X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
				   (const unsigned char *)"AQ", -1, -1, 0);
	X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
				   (const unsigned char *)"UwU", -1, -1, 0);
	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
				   (unsigned char *)"owo.local", -1, -1, 0);
	X509_set_issuer_name(_x509, name);

	X509_set_pubkey(_x509, pkey);
	X509_sign(_x509, pkey, EVP_sha256());

	pthread_barrier_init(&_barrier, NULL, 33);

	pthread_t threads[32];
	for (size_t i = 0; i < 32; i++) {
		pthread_create(&threads[i], NULL, work, NULL);
	}

	pthread_barrier_wait(&_barrier);

	for (size_t i = 0; i < 32; i++) {
		pthread_join(threads[i], NULL);
	}

	X509_free(_x509);
	X509_NAME_free(name);
	EVP_PKEY_free(pkey);
}