Search code examples
copensslx509

How do you remove an extension from an X509?


I am creating an api for modifying X509 certificates in C and I want to add a way to remove an extension (e.g. subjectNameAlt). How would I do this via the OpenSSL API?


Solution

  • Paul's answer is freeing a pointer returned from X509_get_ext, which the documentation explicitly says not to do.. As stated by the documentation:

    X509v3_get_ext() [and X509_get_ext()] retrieves extension loc from x. The index loc can take any value from 0 to X509_get_ext_count(x) - 1. The returned extension is an internal pointer which must not be freed up by the application.

    The correct way to free the extension is as follows.

    int idx = X509_get_ext_by_NID( cert, nid, -1 ); //get the index
    X509_EXTENSION *ext = X509_get_ext(cert, idx); //get the extension
    if (ext != NULL){ //check that the extension was found
        X509_EXTENSION *tmp = X509_delete_ext(cert, idx); //delete the extension
        X509_EXTENSION_free(tmp); //free the memory
    }