I am trying to write a certificate verification function in C using the openssl library. Since the certificate I'm checking is self-signed and expired, I expect X509_verify_cert () to return an error (the return value is 1, and instead of the error store_ctx-> instead of X509_V_OK). ' openssl check my_pem_cert_file :
error 18 at 0 depth lookup:self signed certificate error 10 at 0 depth lookup:certificate has expired
What am I doing wrong? Here is my code:
static int cert_verify_callback(int ok, X509_STORE_CTX *ctx) { if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) { return 1; } return ok; } int cert_validate(const char* certFileName) { BIO *pBio = NULL; X509 *pX509 = NULL; X509 *CA = NULL; X509_STORE *cert_store = NULL; X509_STORE_CTX *store_ctx = NULL; STACK_OF(X509) *stack_of_x509 = NULL; time_t check_time; int store_ctx_error; int store_ctx_error_depth; pBio = BIO_new( BIO_s_file_internal() ); if(pBio == NULL) if(BIO_read_filename(pBio, certFileName) <= 0) pX509 = PEM_read_bio_X509(pBio, NULL, NULL, NULL); if (pX509 == NULL) if( (cert_store= X509_STORE_new()) == NULL) if( (store_ctx= X509_STORE_CTX_new()) == NULL) if( !X509_STORE_CTX_init(store_ctx, cert_store, CA, stack_of_x509) ) X509_STORE_CTX_set_cert(store_ctx, pX509); time(&check_time); X509_STORE_CTX_set_time(store_ctx, 0, check_time); X509_STORE_CTX_set_flags(store_ctx, X509_V_FLAG_USE_CHECK_TIME); X509_STORE_set_verify_cb_func(store_ctx, cert_verify_callback); switch( X509_verify_cert(store_ctx) ) { case 1: printf("The certificate is valid\n"); break; case -1: case 0: printf("The certificate is not valid\n"); store_ctx_error= X509_STORE_CTX_get_error(store_ctx); store_ctx_error_depth= X509_STORE_CTX_get_error_depth(store_ctx); printf("Error %d at %d depth: %s\n", store_ctx_error, store_ctx_error_depth, X509_verify_cert_error_string(store_ctx->error)); default: break; } }
When checking a self-signed and expired certificate, my function prints: Error 0 to 0 depth: ok
source share