1 /* Extract X.509 certificate in DER form from PKCS#11 or PEM.
3 * Copyright © 2014 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 General Public Licence
11 * as published by the Free Software Foundation; either version
12 * 2 of the Licence, or (at your option) any later version.
22 #include <arpa/inet.h>
23 #include <openssl/bio.h>
24 #include <openssl/evp.h>
25 #include <openssl/pem.h>
26 #include <openssl/pkcs7.h>
27 #include <openssl/err.h>
28 #include <openssl/engine.h>
30 #define PKEY_ID_PKCS7 2
32 static __attribute__((noreturn))
36 "Usage: scripts/extract-cert <source> <dest>\n");
40 static void display_openssl_errors(int l)
46 if (ERR_peek_error() == 0)
48 fprintf(stderr, "At main.c:%d:\n", l);
50 while ((e = ERR_get_error_line(&file, &line))) {
51 ERR_error_string(e, buf);
52 fprintf(stderr, "- SSL %s: %s:%d\n", buf, file, line);
56 static void drain_openssl_errors(void)
61 if (ERR_peek_error() == 0)
63 while (ERR_get_error_line(&file, &line)) {}
66 #define ERR(cond, fmt, ...) \
68 bool __cond = (cond); \
69 display_openssl_errors(__LINE__); \
71 err(1, fmt, ## __VA_ARGS__); \
75 static const char *key_pass;
77 int main(int argc, char **argv)
79 char *cert_src, *cert_dst;
83 OpenSSL_add_all_algorithms();
84 ERR_load_crypto_strings();
87 key_pass = getenv("KBUILD_SIGN_PIN");
95 if (!strncmp(cert_src, "pkcs11:", 7)) {
102 parms.cert_id = cert_src;
105 ENGINE_load_builtin_engines();
106 drain_openssl_errors();
107 e = ENGINE_by_id("pkcs11");
108 ERR(!e, "Load PKCS#11 ENGINE");
110 drain_openssl_errors();
112 ERR(1, "ENGINE_init");
114 ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN");
115 ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1);
116 ERR(!parms.cert, "Get X.509 from PKCS#11");
119 b = BIO_new_file(cert_src, "rb");
120 ERR(!b, "%s", cert_src);
121 x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
122 ERR(!x509, "%s", cert_src);
126 b = BIO_new_file(cert_dst, "wb");
127 ERR(!b, "%s", cert_dst);
128 ERR(!i2d_X509_bio(b, x509), cert_dst);