1 /* Extract X.509 certificate in DER form from PKCS#11 or PEM.
3 * Copyright © 2014-2015 Red Hat, Inc. All Rights Reserved.
4 * Copyright © 2015 Intel Corporation.
6 * Authors: David Howells <dhowells@redhat.com>
7 * David Woodhouse <dwmw2@infradead.org>
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the licence, or (at your option) any later version.
21 #include <openssl/bio.h>
22 #include <openssl/pem.h>
23 #include <openssl/err.h>
24 #include <openssl/engine.h>
27 * OpenSSL 3.0 deprecates the OpenSSL's ENGINE API.
29 * Remove this if/when that API is no longer used
31 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
33 #define PKEY_ID_PKCS7 2
35 static __attribute__((noreturn))
39 "Usage: extract-cert <source> <dest>\n");
43 static void display_openssl_errors(int l)
49 if (ERR_peek_error() == 0)
51 fprintf(stderr, "At main.c:%d:\n", l);
53 while ((e = ERR_get_error_line(&file, &line))) {
54 ERR_error_string(e, buf);
55 fprintf(stderr, "- SSL %s: %s:%d\n", buf, file, line);
59 static void drain_openssl_errors(void)
64 if (ERR_peek_error() == 0)
66 while (ERR_get_error_line(&file, &line)) {}
69 #define ERR(cond, fmt, ...) \
71 bool __cond = (cond); \
72 display_openssl_errors(__LINE__); \
74 err(1, fmt, ## __VA_ARGS__); \
78 static const char *key_pass;
80 static char *cert_dst;
81 static int kbuild_verbose;
83 static void write_cert(X509 *x509)
88 wb = BIO_new_file(cert_dst, "wb");
89 ERR(!wb, "%s", cert_dst);
91 X509_NAME_oneline(X509_get_subject_name(x509), buf, sizeof(buf));
92 ERR(!i2d_X509_bio(wb, x509), "%s", cert_dst);
94 fprintf(stderr, "Extracted cert: %s\n", buf);
97 int main(int argc, char **argv)
101 OpenSSL_add_all_algorithms();
102 ERR_load_crypto_strings();
105 kbuild_verbose = atoi(getenv("KBUILD_VERBOSE")?:"0");
107 key_pass = getenv("KBUILD_SIGN_PIN");
116 /* Invoked with no input; create empty file */
117 FILE *f = fopen(cert_dst, "wb");
118 ERR(!f, "%s", cert_dst);
121 } else if (!strncmp(cert_src, "pkcs11:", 7)) {
128 parms.cert_id = cert_src;
131 ENGINE_load_builtin_engines();
132 drain_openssl_errors();
133 e = ENGINE_by_id("pkcs11");
134 ERR(!e, "Load PKCS#11 ENGINE");
136 drain_openssl_errors();
138 ERR(1, "ENGINE_init");
140 ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN");
141 ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1);
142 ERR(!parms.cert, "Get X.509 from PKCS#11");
143 write_cert(parms.cert);
148 b = BIO_new_file(cert_src, "rb");
149 ERR(!b, "%s", cert_src);
152 x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
154 unsigned long err = ERR_peek_last_error();
155 if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
156 ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
161 ERR(!x509, "%s", cert_src);