Skip to content

Commit b800d29

Browse files
sam-githubaddaleax
authored andcommitted
src: in-source comments and minor TLS cleanups
Renamed some internal C++ methods and properties for consistency, and commented SSL I/O. - Rename waiting_new_session_ after is_waiting_new_session(), instead of using reverse naming (new_session_wait_), and change "waiting" to "awaiting". - Make TLSWrap::ClearIn() return void, the value is never used. - Fix a getTicketKeys() cut-n-paste error. Since it doesn't use the arguments, remove them from the js wrapper. - Remove call of setTicketKeys(getTicketKeys()), its a no-op. PR-URL: nodejs#25713 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Michael Dawson <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 6e849c3 commit b800d29

8 files changed

+84
-37
lines changed

lib/_tls_wrap.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -929,8 +929,8 @@ Server.prototype._setServerData = function(data) {
929929
};
930930

931931

932-
Server.prototype.getTicketKeys = function getTicketKeys(keys) {
933-
return this._sharedCreds.context.getTicketKeys(keys);
932+
Server.prototype.getTicketKeys = function getTicketKeys() {
933+
return this._sharedCreds.context.getTicketKeys();
934934
};
935935

936936

src/node_crypto.cc

+3-2
Original file line numberDiff line numberDiff line change
@@ -1475,7 +1475,7 @@ int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
14751475
reinterpret_cast<const char*>(session_id),
14761476
session_id_length).ToLocalChecked();
14771477
Local<Value> argv[] = { session, buff };
1478-
w->new_session_wait_ = true;
1478+
w->awaiting_new_session_ = true;
14791479
w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
14801480

14811481
return 0;
@@ -2003,6 +2003,7 @@ void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
20032003

20042004
ClearErrorOnReturn clear_error_on_return;
20052005

2006+
// XXX(sam) Return/throw an error, don't discard the SSL error reason.
20062007
bool yes = SSL_renegotiate(w->ssl_.get()) == 1;
20072008
args.GetReturnValue().Set(yes);
20082009
}
@@ -2036,7 +2037,7 @@ template <class Base>
20362037
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
20372038
Base* w;
20382039
ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2039-
w->new_session_wait_ = false;
2040+
w->awaiting_new_session_ = false;
20402041
w->NewSessionDoneCb();
20412042
}
20422043

src/node_crypto.h

+3-3
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ class SSLWrap {
218218
kind_(kind),
219219
next_sess_(nullptr),
220220
session_callbacks_(false),
221-
new_session_wait_(false),
221+
awaiting_new_session_(false),
222222
cert_cb_(nullptr),
223223
cert_cb_arg_(nullptr),
224224
cert_cb_running_(false) {
@@ -234,7 +234,7 @@ class SSLWrap {
234234
inline void enable_session_callbacks() { session_callbacks_ = true; }
235235
inline bool is_server() const { return kind_ == kServer; }
236236
inline bool is_client() const { return kind_ == kClient; }
237-
inline bool is_waiting_new_session() const { return new_session_wait_; }
237+
inline bool is_awaiting_new_session() const { return awaiting_new_session_; }
238238
inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; }
239239

240240
protected:
@@ -324,7 +324,7 @@ class SSLWrap {
324324
SSLSessionPointer next_sess_;
325325
SSLPointer ssl_;
326326
bool session_callbacks_;
327-
bool new_session_wait_;
327+
bool awaiting_new_session_;
328328

329329
// SSL_set_cert_cb
330330
CertCb cert_cb_;

src/node_crypto_bio.h

+6-5
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ namespace node {
3434
namespace crypto {
3535

3636
// This class represents buffers for OpenSSL I/O, implemented as a singly-linked
37-
// list of chunks. It can be used both for writing data from Node to OpenSSL
38-
// and back, but only one direction per instance.
37+
// list of chunks. It can be used either for writing data from Node to OpenSSL,
38+
// or for reading data back, but not both.
3939
// The structure is only accessed, and owned by, the OpenSSL BIOPointer
4040
// (a.k.a. std::unique_ptr<BIO>).
4141
class NodeBIO : public MemoryRetainer {
@@ -80,11 +80,12 @@ class NodeBIO : public MemoryRetainer {
8080
// Put `len` bytes from `data` into buffer
8181
void Write(const char* data, size_t size);
8282

83-
// Return pointer to internal data and amount of
84-
// contiguous data available for future writes
83+
// Return pointer to contiguous block of reserved data and the size available
84+
// for future writes. Call Commit() once the write is complete.
8585
char* PeekWritable(size_t* size);
8686

87-
// Commit reserved data
87+
// Specify how much data was written into the block returned by
88+
// PeekWritable().
8889
void Commit(size_t size);
8990

9091

src/node_crypto_clienthello.h

+3
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@
3030
namespace node {
3131
namespace crypto {
3232

33+
// Parse the client hello so we can do async session resumption. OpenSSL's
34+
// session resumption uses synchronous callbacks, see SSL_CTX_sess_set_get_cb
35+
// and get_session_cb.
3336
class ClientHelloParser {
3437
public:
3538
inline ClientHelloParser();

src/stream_wrap.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ void LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) {
222222
type = uv_pipe_pending_type(reinterpret_cast<uv_pipe_t*>(stream()));
223223
}
224224

225-
// We should not be getting this callback if someone as already called
225+
// We should not be getting this callback if someone has already called
226226
// uv_close() on the handle.
227227
CHECK_EQ(persistent().IsEmpty(), false);
228228

src/tls_wrap.cc

+43-17
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@ void TLSWrap::InitSSL() {
116116
#endif // SSL_MODE_RELEASE_BUFFERS
117117

118118
SSL_set_app_data(ssl_.get(), this);
119+
// Using InfoCallback isn't how we are supposed to check handshake progress:
120+
// https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
121+
//
122+
// Note on when this gets called on various openssl versions:
123+
// https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
119124
SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
120125

121126
if (is_server()) {
@@ -194,6 +199,9 @@ void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
194199

195200
// Send ClientHello handshake
196201
CHECK(wrap->is_client());
202+
// Seems odd to read when when we want to send, but SSL_read() triggers a
203+
// handshake if a session isn't established, and handshake will cause
204+
// encrypted data to become available for output.
197205
wrap->ClearOut();
198206
wrap->EncOut();
199207
}
@@ -243,7 +251,7 @@ void TLSWrap::EncOut() {
243251
return;
244252

245253
// Wait for `newSession` callback to be invoked
246-
if (is_waiting_new_session())
254+
if (is_awaiting_new_session())
247255
return;
248256

249257
// Split-off queue
@@ -253,7 +261,7 @@ void TLSWrap::EncOut() {
253261
if (ssl_ == nullptr)
254262
return;
255263

256-
// No data to write
264+
// No encrypted output ready to write to the underlying stream.
257265
if (BIO_pending(enc_out_) == 0) {
258266
if (pending_cleartext_input_.empty())
259267
InvokeQueued(0);
@@ -442,13 +450,13 @@ void TLSWrap::ClearOut() {
442450
}
443451

444452

445-
bool TLSWrap::ClearIn() {
453+
void TLSWrap::ClearIn() {
446454
// Ignore cycling data if ClientHello wasn't yet parsed
447455
if (!hello_parser_.IsEnded())
448-
return false;
456+
return;
449457

450458
if (ssl_ == nullptr)
451-
return false;
459+
return;
452460

453461
std::vector<uv_buf_t> buffers;
454462
buffers.swap(pending_cleartext_input_);
@@ -468,8 +476,9 @@ bool TLSWrap::ClearIn() {
468476

469477
// All written
470478
if (i == buffers.size()) {
479+
// We wrote all the buffers, so no writes failed (written < 0 on failure).
471480
CHECK_GE(written, 0);
472-
return true;
481+
return;
473482
}
474483

475484
// Error or partial write
@@ -481,6 +490,8 @@ bool TLSWrap::ClearIn() {
481490
Local<Value> arg = GetSSLError(written, &err, &error_str);
482491
if (!arg.IsEmpty()) {
483492
write_callback_scheduled_ = true;
493+
// XXX(sam) Should forward an error object with .code/.function/.etc, if
494+
// possible.
484495
InvokeQueued(UV_EPROTO, error_str.c_str());
485496
} else {
486497
// Push back the not-yet-written pending buffers into their queue.
@@ -491,7 +502,7 @@ bool TLSWrap::ClearIn() {
491502
buffers.end());
492503
}
493504

494-
return false;
505+
return;
495506
}
496507

497508

@@ -547,6 +558,7 @@ void TLSWrap::ClearError() {
547558
}
548559

549560

561+
// Called by StreamBase::Write() to request async write of clear text into SSL.
550562
int TLSWrap::DoWrite(WriteWrap* w,
551563
uv_buf_t* bufs,
552564
size_t count,
@@ -560,18 +572,26 @@ int TLSWrap::DoWrite(WriteWrap* w,
560572
}
561573

562574
bool empty = true;
563-
564-
// Empty writes should not go through encryption process
565575
size_t i;
566-
for (i = 0; i < count; i++)
576+
for (i = 0; i < count; i++) {
567577
if (bufs[i].len > 0) {
568578
empty = false;
569579
break;
570580
}
581+
}
582+
583+
// We want to trigger a Write() on the underlying stream to drive the stream
584+
// system, but don't want to encrypt empty buffers into a TLS frame, so see
585+
// if we can find something to Write().
586+
// First, call ClearOut(). It does an SSL_read(), which might cause handshake
587+
// or other internal messages to be encrypted. If it does, write them later
588+
// with EncOut().
589+
// If there is still no encrypted output, call Write(bufs) on the underlying
590+
// stream. Since the bufs are empty, it won't actually write non-TLS data
591+
// onto the socket, we just want the side-effects. After, make sure the
592+
// WriteWrap was accepted by the stream, or that we call Done() on it.
571593
if (empty) {
572594
ClearOut();
573-
// However, if there is any data that should be written to the socket,
574-
// the callback should not be invoked immediately
575595
if (BIO_pending(enc_out_) == 0) {
576596
CHECK_NULL(current_empty_write_);
577597
current_empty_write_ = w;
@@ -591,7 +611,7 @@ int TLSWrap::DoWrite(WriteWrap* w,
591611
CHECK_NULL(current_write_);
592612
current_write_ = w;
593613

594-
// Write queued data
614+
// Write encrypted data to underlying stream and call Done().
595615
if (empty) {
596616
EncOut();
597617
return 0;
@@ -610,17 +630,20 @@ int TLSWrap::DoWrite(WriteWrap* w,
610630
if (i != count) {
611631
int err;
612632
Local<Value> arg = GetSSLError(written, &err, &error_);
633+
634+
// If we stopped writing because of an error, it's fatal, discard the data.
613635
if (!arg.IsEmpty()) {
614636
current_write_ = nullptr;
615637
return UV_EPROTO;
616638
}
617639

640+
// Otherwise, save unwritten data so it can be written later by ClearIn().
618641
pending_cleartext_input_.insert(pending_cleartext_input_.end(),
619642
&bufs[i],
620643
&bufs[count]);
621644
}
622645

623-
// Try writing data immediately
646+
// Write any encrypted/handshake output that may be ready.
624647
EncOut();
625648

626649
return 0;
@@ -652,17 +675,20 @@ void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
652675
return;
653676
}
654677

655-
// Only client connections can receive data
656678
if (ssl_ == nullptr) {
657679
EmitRead(UV_EPROTO);
658680
return;
659681
}
660682

661-
// Commit read data
683+
// Commit the amount of data actually read into the peeked/allocated buffer
684+
// from the underlying stream.
662685
crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
663686
enc_in->Commit(nread);
664687

665-
// Parse ClientHello first
688+
// Parse ClientHello first, if we need to. It's only parsed if session event
689+
// listeners are used on the server side. "ended" is the initial state, so
690+
// can mean parsing was never started, or that parsing is finished. Either
691+
// way, ended means we can give the buffered data to SSL.
666692
if (!hello_parser_.IsEnded()) {
667693
size_t avail = 0;
668694
uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));

src/tls_wrap.h

+23-7
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,9 @@ class TLSWrap : public AsyncWrap,
7171
uv_buf_t* bufs,
7272
size_t count,
7373
uv_stream_t* send_handle) override;
74+
// Return error_ string or nullptr if it's empty.
7475
const char* Error() const override;
76+
// Reset error_ string to empty. Not related to "clear text".
7577
void ClearError() override;
7678

7779
void NewSessionDoneCb();
@@ -104,11 +106,22 @@ class TLSWrap : public AsyncWrap,
104106

105107
static void SSLInfoCallback(const SSL* ssl_, int where, int ret);
106108
void InitSSL();
107-
void EncOut();
108-
bool ClearIn();
109-
void ClearOut();
109+
// SSL has a "clear" text (unencrypted) side (to/from the node API) and
110+
// encrypted ("enc") text side (to/from the underlying socket/stream).
111+
// On each side data flows "in" or "out" of SSL context.
112+
//
113+
// EncIn() doesn't exist. Encrypted data is pushed from underlying stream into
114+
// enc_in_ via the stream listener's OnStreamAlloc()/OnStreamRead() interface.
115+
void EncOut(); // Write encrypted data from enc_out_ to underlying stream.
116+
void ClearIn(); // SSL_write() clear data "in" to SSL.
117+
void ClearOut(); // SSL_read() clear text "out" from SSL.
118+
119+
// Call Done() on outstanding WriteWrap request.
110120
bool InvokeQueued(int status, const char* error_str = nullptr);
111121

122+
// Drive the SSL state machine by attempting to SSL_read() and SSL_write() to
123+
// it. Transparent handshakes mean SSL_read() might trigger I/O on the
124+
// underlying stream even if there is no clear text to read or write.
112125
inline void Cycle() {
113126
// Prevent recursion
114127
if (++cycle_depth_ > 1)
@@ -117,6 +130,7 @@ class TLSWrap : public AsyncWrap,
117130
for (; cycle_depth_ > 0; cycle_depth_--) {
118131
ClearIn();
119132
ClearOut();
133+
// EncIn() doesn't exist, it happens via stream listener callbacks.
120134
EncOut();
121135
}
122136
}
@@ -138,16 +152,18 @@ class TLSWrap : public AsyncWrap,
138152
static void SetVerifyMode(const v8::FunctionCallbackInfo<v8::Value>& args);
139153
static void EnableSessionCallbacks(
140154
const v8::FunctionCallbackInfo<v8::Value>& args);
141-
static void EnableCertCb(
142-
const v8::FunctionCallbackInfo<v8::Value>& args);
155+
static void EnableTrace(const v8::FunctionCallbackInfo<v8::Value>& args);
156+
static void EnableCertCb(const v8::FunctionCallbackInfo<v8::Value>& args);
143157
static void DestroySSL(const v8::FunctionCallbackInfo<v8::Value>& args);
144158
static void GetServername(const v8::FunctionCallbackInfo<v8::Value>& args);
145159
static void SetServername(const v8::FunctionCallbackInfo<v8::Value>& args);
146160
static int SelectSNIContextCallback(SSL* s, int* ad, void* arg);
147161

148162
crypto::SecureContext* sc_;
149-
BIO* enc_in_ = nullptr;
150-
BIO* enc_out_ = nullptr;
163+
// BIO buffers hold encrypted data.
164+
BIO* enc_in_ = nullptr; // StreamListener fills this for SSL_read().
165+
BIO* enc_out_ = nullptr; // SSL_write()/handshake fills this for EncOut().
166+
// Waiting for ClearIn() to pass to SSL_write().
151167
std::vector<uv_buf_t> pending_cleartext_input_;
152168
size_t write_size_ = 0;
153169
WriteWrap* current_write_ = nullptr;

0 commit comments

Comments
 (0)