OpenVPN 3 Core Library
Loading...
Searching...
No Matches
dh.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// Wrap a mbed TLS dhm_context object (Diffie Hellman parameters).
13
14#ifndef OPENVPN_MBEDTLS_PKI_DH_H
15#define OPENVPN_MBEDTLS_PKI_DH_H
16
17#include <string>
18#include <sstream>
19#include <cstring>
20
21#include <mbedtls/x509.h>
22
25#include <openvpn/common/rc.hpp>
27
29
30class DH : public RC<thread_unsafe_refcount>
31{
32 public:
33 typedef RCPtr<DH> Ptr;
34
36 : dhc(nullptr)
37 {
38 }
39
40 DH(const std::string &dh_txt, const std::string &title)
41 : dhc(nullptr)
42 {
43 try
44 {
45 parse(dh_txt, title);
46 }
47 catch (...)
48 {
49 dealloc();
50 throw;
51 }
52 }
53
54 void parse(const std::string &dh_txt, const std::string &title)
55 {
56 alloc();
57 // dh_txt.length() is increased by 1 as it does not include the NULL-terminator
58 // which mbedtls_dhm_parse_dhm() expects to see.
59 const int status = mbedtls_dhm_parse_dhm(dhc,
60 (const unsigned char *)dh_txt.c_str(),
61 dh_txt.length() + 1);
62 if (status < 0)
63 {
64 throw MbedTLSException("error parsing " + title + " DH parameters", status);
65 }
66 if (status > 0)
67 {
68 std::ostringstream os;
69 os << status << " DH parameters in " << title << " failed to parse";
70 throw MbedTLSException(os.str());
71 }
72 // store PEM data to allow extraction
73 pem_dhc = dh_txt;
74 }
75
76 std::string extract() const
77 {
78 return std::string(pem_dhc);
79 }
80
81 mbedtls_dhm_context *get() const
82 {
83 return dhc;
84 }
85
87 {
88 dealloc();
89 }
90
91 private:
92 void alloc()
93 {
94 if (!dhc)
95 {
96 dhc = new mbedtls_dhm_context;
97 mbedtls_dhm_init(dhc);
98 }
99 }
100
101 void dealloc()
102 {
103 if (dhc)
104 {
105 mbedtls_dhm_free(dhc);
106 delete dhc;
107 dhc = nullptr;
108 }
109 }
110
111 mbedtls_dhm_context *dhc;
112 std::string pem_dhc;
113};
114} // namespace openvpn::MbedTLSPKI
115
116#endif
mbedtls_dhm_context * get() const
Definition dh.hpp:81
std::string pem_dhc
Definition dh.hpp:112
void parse(const std::string &dh_txt, const std::string &title)
Definition dh.hpp:54
std::string extract() const
Definition dh.hpp:76
mbedtls_dhm_context * dhc
Definition dh.hpp:111
DH(const std::string &dh_txt, const std::string &title)
Definition dh.hpp:40
RCPtr< DH > Ptr
Definition dh.hpp:33
The smart pointer class.
Definition rc.hpp:119
Reference count base class for objects tracked by RCPtr. Disallows copying and assignment.
Definition rc.hpp:912
std::ostringstream os