Skip to content

Bug while reading X509Certificate subjectName #958

@ghost

Description

I stumbled upon this while debugging why my self signed certificate was not verified properly.
The bug is in X509Certificate.cpp:220, in the function X509Certificate::subjectName.
The function X509_NAME_get_text_by_NID is called, and its result is put into a buffer without verifying the result.
There can be self-signed certificates without subject names. In which case, X509_NAME_get_text_by_NID returns -1 and doesn't change the buffer.
Since the return value isn't checked, just random data from the stack is put into an std::string and returned.
To fix it, you must check the return value from X509_NAME_get_text_by_NID and return an empty string if it returns -1 (not found) or -2 (invalid NID).
I'm guessing the same bug exists one function above (X509Certificate::issuerName), but I have not verified this.
Possible fix:

std::string X509Certificate::issuerName(NID nid) const
{
    if (X509_NAME* issuer = X509_get_issuer_name(_pCert))
    {
        char buffer[NAME_BUFFER_SIZE];
        if (X509_NAME_get_text_by_NID(issuer, nid, buffer, sizeof(buffer)) < 0) {
            return std::string();
        }
        return std::string(buffer);
    }
    else return std::string();
}


std::string X509Certificate::subjectName(NID nid) const
{
    if (X509_NAME* subj = X509_get_subject_name(_pCert))
    {
        char buffer[NAME_BUFFER_SIZE];
        if (X509_NAME_get_text_by_NID(subj, nid, buffer, sizeof(buffer)) < 0) {
            return std::string();
        }
        return std::string(buffer);
    }
    else return std::string();
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions