{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtls.cppm
More file actions
319 lines (279 loc) · 11.2 KB
/
Copy pathtls.cppm
File metadata and controls
319 lines (279 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
module;
#include <mbedtls/ssl.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/x509_crt.h>
#include <mbedtls/error.h>
#include <mbedtls/net_sockets.h>
export module mcpplibs.tinyhttps:tls;
import :socket;
import :ca_bundle;
import std;
namespace mcpplibs::tinyhttps {
struct TlsState {
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_context entropy;
mbedtls_x509_crt ca_cert;
TlsState() {
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_entropy_init(&entropy);
mbedtls_x509_crt_init(&ca_cert);
}
~TlsState() {
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
mbedtls_x509_crt_free(&ca_cert);
}
TlsState(const TlsState&) = delete;
TlsState& operator=(const TlsState&) = delete;
};
// BIO callbacks for mbedtls — forward to Socket read/write
static int bio_send(void* ctx, const unsigned char* buf, size_t len) {
auto* sock = static_cast<Socket*>(ctx);
int ret = sock->write(reinterpret_cast<const char*>(buf), static_cast<int>(len));
if (ret <= 0) {
return MBEDTLS_ERR_NET_SEND_FAILED;
}
return ret;
}
// A ZERO IS PASSED THROUGH, AND THAT IS THE WHOLE CONTRACT.
//
// This used to answer a `recv` of 0 — a peer that sent FIN, which is how nearly
// every server ends a connection-close-delimited response — with
// MBEDTLS_ERR_NET_CONN_RESET. mbedtls's own BIO does not: `mbedtls_net_recv`
// returns `read()`'s result unchanged and reserves CONN_RESET for an actual
// ECONNRESET/EPIPE (net_sockets.c). The distinction is not cosmetic, because
// `mbedtls_ssl_fetch_input` tests for exactly this zero —
//
// if (ret == 0) { return MBEDTLS_ERR_SSL_CONN_EOF; } ssl_msg.c:2251, :2320
//
// — and passes any negative value straight through. So the old mapping made an
// orderly end of stream indistinguishable from a transport error, one layer
// below `TlsSocket::read_some`, which then had to call it `Error`. A body whose
// framing IS the close then read as truncated: `download_to_file` set
// `result.error` and `ok()` returned false for a file that had arrived
// complete and correct.
static int bio_recv(void* ctx, unsigned char* buf, size_t len) {
auto* sock = static_cast<Socket*>(ctx);
int ret = sock->read(reinterpret_cast<char*>(buf), static_cast<int>(len));
if (ret < 0) {
return MBEDTLS_ERR_NET_RECV_FAILED;
}
return ret; // 0 means end of stream; mbedtls turns it into SSL_CONN_EOF
}
// WHAT A READ ENDED IN, WHICH `int` COULD NOT SAY.
//
// `TlsSocket::read` returned 0 for a peer that had closed AND for a transport
// that had no bytes ready yet, so every caller had to guess. They all guessed
// the same way — wait once more and try again — and a reader that cannot tell
// "the body ended here" from "nothing yet" cannot decide whether the connection
// is still reusable. That is root cause R3 behind issue #15.
//
// `Eof` is a fact about the stream and `WouldBlock` is a fact about this
// instant; naming them apart is what lets `read_body` below return `Complete`
// rather than a guess.
export enum class ReadStatus { Data, WouldBlock, Eof, Error };
export struct ReadResult {
ReadStatus status { ReadStatus::Error };
int bytes { 0 }; // meaningful only when status == Data
};
export class TlsSocket {
public:
TlsSocket() = default;
~TlsSocket() { close(); }
// Non-copyable
TlsSocket(const TlsSocket&) = delete;
TlsSocket& operator=(const TlsSocket&) = delete;
// Move constructor
TlsSocket(TlsSocket&& other) noexcept
: socket_(std::move(other.socket_))
, state_(std::move(other.state_)) {
// Re-bind BIO to point to our socket_ (not the moved-from one)
if (state_) {
mbedtls_ssl_set_bio(&state_->ssl, &socket_, bio_send, bio_recv, nullptr);
}
}
// Move assignment
TlsSocket& operator=(TlsSocket&& other) noexcept {
if (this != &other) {
close();
socket_ = std::move(other.socket_);
state_ = std::move(other.state_);
// Re-bind BIO to point to our socket_
if (state_) {
mbedtls_ssl_set_bio(&state_->ssl, &socket_, bio_send, bio_recv, nullptr);
}
}
return *this;
}
[[nodiscard]] bool is_valid() const {
return state_ != nullptr && socket_.is_valid();
}
// Connect over an already-established Socket (e.g. a proxy tunnel).
// Takes ownership of the socket and performs TLS handshake on top of it.
bool connect_over(Socket&& socket, const char* host, bool verifySsl) {
socket_ = std::move(socket);
return setup_tls(host, verifySsl);
}
bool connect(const char* host, int port, int timeoutMs, bool verifySsl) {
// Step 1: TCP connect via Socket
if (!socket_.connect(host, port, timeoutMs)) {
return false;
}
return setup_tls(host, verifySsl);
}
// The read that says which of the four things happened. Prefer it over
// `read` below wherever the answer changes what the caller does.
ReadResult read_some(char* buf, int len) {
if (!is_valid()) return { ReadStatus::Error, 0 };
int ret = mbedtls_ssl_read(&state_->ssl,
reinterpret_cast<unsigned char*>(buf), static_cast<size_t>(len));
// Three spellings of "there is nothing more coming", and all three are
// an end of stream rather than a failure: the peer shut the session
// down politely, the transport reached its end (what `bio_recv`'s zero
// becomes), or mbedtls had nothing left to hand back. Most servers do
// NOT send close_notify before closing, so the middle one is the common
// case rather than the exotic one.
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY
|| ret == MBEDTLS_ERR_SSL_CONN_EOF
|| ret == 0) {
return { ReadStatus::Eof, 0 };
}
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
return { ReadStatus::WouldBlock, 0 };
}
if (ret < 0) return { ReadStatus::Error, 0 };
return { ReadStatus::Data, ret };
}
// The older shape, kept because it is exported and callers outside this
// repository use it. It collapses Eof and WouldBlock back into 0, which is
// the ambiguity `read_some` exists to remove.
int read(char* buf, int len) {
auto r = read_some(buf, len);
switch (r.status) {
case ReadStatus::Data: return r.bytes;
case ReadStatus::Eof:
case ReadStatus::WouldBlock: return 0;
case ReadStatus::Error: return -1;
}
return -1;
}
// Returns 0 for "the transport is not ready", which `write_all` answers by
// waiting on the socket rather than by retrying immediately.
int write(const char* buf, int len) {
if (!is_valid()) return -1;
int ret = mbedtls_ssl_write(&state_->ssl,
reinterpret_cast<const unsigned char*>(buf), static_cast<size_t>(len));
if (ret < 0) {
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
return 0;
}
return -1;
}
return ret;
}
void close() {
if (state_) {
mbedtls_ssl_close_notify(&state_->ssl);
state_.reset();
}
socket_.close();
}
bool wait_readable(int timeoutMs) {
// Check if mbedtls has already buffered decrypted data
if (state_ && mbedtls_ssl_get_bytes_avail(&state_->ssl) > 0) {
return true;
}
return socket_.wait_readable(timeoutMs);
}
// TLS back-pressure is a wait, not a failure. `mbedtls_ssl_write` reports
// WANT_WRITE when the record layer cannot flush, and `write` above turns
// that into 0; without something to wait on, `write_all` could only retry
// at once and then give up, which reached the caller as "Write failed".
bool wait_writable(int timeoutMs) {
return socket_.wait_writable(timeoutMs);
}
private:
Socket socket_;
std::unique_ptr<TlsState> state_;
bool setup_tls(const char* host, bool verifySsl) {
state_ = std::make_unique<TlsState>();
int ret = mbedtls_ctr_drbg_seed(
&state_->ctr_drbg, mbedtls_entropy_func, &state_->entropy,
nullptr, 0);
if (ret != 0) {
state_.reset();
socket_.close();
return false;
}
ret = mbedtls_ssl_config_defaults(
&state_->conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0) {
state_.reset();
socket_.close();
return false;
}
mbedtls_ssl_conf_rng(&state_->conf, mbedtls_ctr_drbg_random, &state_->ctr_drbg);
// mbedTLS 3.6 TLS 1.3 key derivation can fail in statically-linked
// builds; cap at TLS 1.2 which works reliably everywhere.
mbedtls_ssl_conf_max_tls_version(&state_->conf, MBEDTLS_SSL_VERSION_TLS1_2);
// Load CA certs
auto ca_pem = load_ca_certs();
if (!ca_pem.empty()) {
ret = mbedtls_x509_crt_parse(
&state_->ca_cert,
reinterpret_cast<const unsigned char*>(ca_pem.c_str()),
ca_pem.size() + 1); // +1 for null terminator required by mbedtls
// ret > 0 means some certs failed to parse but others succeeded — acceptable
if (ret < 0) {
state_.reset();
socket_.close();
return false;
}
mbedtls_ssl_conf_ca_chain(&state_->conf, &state_->ca_cert, nullptr);
}
// Certificate verification
// Use OPTIONAL (not REQUIRED) so handshake succeeds even if the CA
// bundle is incomplete; callers that need strict verification can
// inspect the verification result after handshake.
if (verifySsl) {
mbedtls_ssl_conf_authmode(&state_->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
} else {
mbedtls_ssl_conf_authmode(&state_->conf, MBEDTLS_SSL_VERIFY_NONE);
}
ret = mbedtls_ssl_setup(&state_->ssl, &state_->conf);
if (ret != 0) {
state_.reset();
socket_.close();
return false;
}
// Set hostname for SNI
ret = mbedtls_ssl_set_hostname(&state_->ssl, host);
if (ret != 0) {
state_.reset();
socket_.close();
return false;
}
// Set BIO callbacks using our Socket
mbedtls_ssl_set_bio(&state_->ssl, &socket_, bio_send, bio_recv, nullptr);
// Perform TLS handshake
while ((ret = mbedtls_ssl_handshake(&state_->ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
state_.reset();
socket_.close();
return false;
}
}
return true;
}
};
} // namespace mcpplibs::tinyhttps
You can’t perform that action at this time.
