OpenVPN 3 Core Library
Loading...
Searching...
No Matches
pkcs7verify.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Verify a PKCS7 signature
13
14#ifndef OPENVPN_OPENSSL_SIGN_PKCS7VERIFY_H
15#define OPENVPN_OPENSSL_SIGN_PKCS7VERIFY_H
16
17#include <string>
18
19#include <openssl/ssl.h>
20#include <openssl/bio.h>
21#include <openssl/pkcs7.h>
22
27
29/*
30 * Verify PKCS7 signature.
31 * On success, return.
32 * On fail, throw exception.
33 */
34inline void verify_pkcs7(const std::list<OpenSSLPKI::X509> &certs,
35 const std::string &sig,
36 const std::string &data)
37{
38 STACK_OF(X509) *x509_stack = nullptr;
39 BIO *in = nullptr;
40 PKCS7 *p7 = nullptr;
41
42 auto clean = Cleanup([&]()
43 {
44 if (x509_stack)
45 sk_X509_free(x509_stack);
46 if (in)
47 BIO_free(in);
48 if (p7)
49 PKCS7_free(p7); });
50
51 /* create x509_stack from cert */
52 x509_stack = sk_X509_new_null();
53 for (const auto &cert : certs)
54 sk_X509_push(x509_stack, cert.obj());
55
56 /* get signature */
57 in = BIO_new_mem_buf(sig.c_str(), numeric_cast<int>(sig.length()));
58 p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
59 if (!p7)
60 throw OpenSSLException("OpenSSLSign::verify_pkcs7: failed to parse pkcs7 signature");
61 BIO_free(in);
62 in = nullptr;
63
64 /* get data */
65 in = BIO_new_mem_buf(data.c_str(), numeric_cast<int>(data.length()));
66
67 /* OpenSSL 1.0.2e and higher no longer allows calling PKCS7_verify
68 with both data and content. Empty out the content if present.
69 Just calling PKCS7_set_detached call lead to a null pointer access */
70 if (!PKCS7_is_detached(p7))
71 PKCS7_set_detached(p7, 1);
72
73 /* do the verify */
74 if (PKCS7_verify(p7, x509_stack, nullptr, in, nullptr, PKCS7_NOVERIFY) != 1)
75 throw OpenSSLException("OpenSSLSign::verify_pkcs7: verification failed");
76}
77} // namespace openvpn::OpenSSLSign
78
79#endif
void verify_pkcs7(const std::list< OpenSSLPKI::X509 > &certs, const std::string &sig, const std::string &data)
CleanupType< F > Cleanup(F method) noexcept
Definition cleanup.hpp:43