36#include <openssl/pem.h>
37#include <openssl/x509.h>
38#include <openssl/x509_vfy.h>
43 while ((opt = getopt(argc, argv,
"hvV:")) != EOF) {
46 if (!strncmp(
"LOG_NULL", optarg, 8))
48 else if (!strncmp(
"LOG_NOTICE", optarg, 10))
50 else if (!strncmp(
"LOG_INFO", optarg, 8))
52 else if (!strncmp(
"LOG_ERR", optarg, 7))
54 else if (!strncmp(
"LOG_DEBUG", optarg, 9))
57 fprintf(stderr,
"Unknown log level %s\n", optarg);
62 fprintf(stderr,
"ex_x509\n");
66 fprintf(stderr,
"usage: %s [-V LOG_LEVEL]\n", argv[0]);
74 BIO* bca = BIO_new_mem_buf(ca_pem->
data, (
int)ca_pem->
written);
75 BIO* bleaf = BIO_new_mem_buf(leaf_pem->
data, (
int)leaf_pem->
written);
76 X509* ca = bca ? PEM_read_bio_X509(bca, NULL, NULL, NULL) : NULL;
77 X509* leaf = bleaf ? PEM_read_bio_X509(bleaf, NULL, NULL, NULL) : NULL;
78 X509_STORE* store = X509_STORE_new();
79 X509_STORE_CTX* ctx = X509_STORE_CTX_new();
81 if (ca && leaf && store && ctx) {
82 X509_STORE_add_cert(store, ca);
83 if (X509_STORE_CTX_init(ctx, store, leaf, NULL) == 1)
84 ok = (X509_verify_cert(ctx) == 1);
87 X509_STORE_CTX_free(ctx);
89 X509_STORE_free(store);
101int main(
int argc,
char** argv) {
102 N_STR* ca_cert = NULL;
103 N_STR* ca_key = NULL;
105 const char* hosts[] = {
"example.com",
"127.0.0.1"};
112 if (
n_x509_generate_ca(
"Nilorea Test CA", 3650, &ca_cert, &ca_key) != 0 || !ca_cert || !ca_key) {
117 for (i = 0; i <
sizeof(hosts) /
sizeof(hosts[0]); i++) {
118 N_STR* leaf_cert = NULL;
119 N_STR* leaf_key = NULL;
120 if (
n_x509_mint_host_cert(hosts[i], ca_cert, ca_key, 825, &leaf_cert, &leaf_key) != 0 || !leaf_cert || !leaf_key) {
124 n_log(
LOG_ERR,
"leaf for %s does not verify against the CA", hosts[i]);
void process_args(int argc, char **argv)
static int verify_chain(const N_STR *ca_pem, const N_STR *leaf_pem)
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_DEBUG
debug-level messages
#define LOG_ERR
error conditions
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
#define LOG_NOTICE
normal but significant condition
#define LOG_NULL
no log output
#define LOG_INFO
informational
size_t written
number of meaningful bytes in data, excluding the null terminator; the size including the null termin...
#define free_nstr(__ptr)
free a N_STR structure and set the pointer to NULL
A box including a string and his lenght.
int n_x509_generate_ca(const char *cn, int days, N_STR **ca_cert_pem, N_STR **ca_key_pem)
Generate a self-signed certificate authority (CA) keypair and cert.
int n_x509_keypair_pem(int bits, N_STR **key_pem)
Generate an RSA private key and return it as a PEM string.
int n_x509_mint_host_cert(const char *host, const N_STR *ca_cert_pem, const N_STR *ca_key_pem, int days, N_STR **leaf_cert_pem, N_STR **leaf_key_pem)
Mint a per-host leaf certificate signed by the given CA.
N_STR and string function declaration.
X.509 helpers: self-signed CA generation and per-host leaf minting.