void addExtensions()

in azure-protected-vm-secrets/Linux/OsslX509.cpp [128:166]


void addExtensions(X509* cert, X509* issuer, int is_ca, int pathlen = -1) {
    X509V3_CTX ctx;
    X509V3_set_ctx_nodb(&ctx);
    X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);

    // Add Basic Constraints
    std::string bc;
    if (is_ca) {
        bc = "critical,CA:TRUE";
        if (pathlen >= 0) {
            bc += ",pathlen:" + std::to_string(pathlen);
        }
    } else {
        bc = "critical,CA:FALSE";
    }
    std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)> ex(
        X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints, bc.c_str()), &X509_EXTENSION_free);
    if (!ex || X509_add_ext(cert, ex.get(), -1) != 1) {
        throw OsslError(ERR_get_error(), "Failed to add Basic Constraints extension");
    }

    std::string ku = is_ca ? "critical,keyCertSign,cRLSign" : "critical,digitalSignature,keyEncipherment";
    ex.reset(X509V3_EXT_conf_nid(NULL, &ctx, NID_key_usage, ku.c_str()));
    if (!ex || X509_add_ext(cert, ex.get(), -1) != 1) {
        throw OsslError(ERR_get_error(), "Failed to add Key Usage extension");
    }

    ex.reset(X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, "hash"));
    if (!ex || X509_add_ext(cert, ex.get(), -1) != 1) {
        throw OsslError(ERR_get_error(), "Failed to add Subject Key Identifier extension");
    }

    if (issuer != NULL && issuer != cert) {
        ex.reset(X509V3_EXT_conf_nid(NULL, &ctx, NID_authority_key_identifier, "keyid:always"));
        if (!ex || X509_add_ext(cert, ex.get(), -1) != 1) {
            throw OsslError(ERR_get_error(), "Failed to add Authority Key Identifier extension");
        }
    }
}