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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "CommonSocketControl.h"
#include "PublicKeyPinningService.h"
#include "SharedCertVerifier.h"
#include "SharedSSLState.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/dom/Promise.h"
#include "nsICertOverrideService.h"
#include "nsISocketProvider.h"
#include "nsITlsHandshakeListener.h"
#include "nsNSSComponent.h"
#include "nsNSSHelper.h"
#include "ssl.h"
#include "sslt.h"
using namespace mozilla;
extern LazyLogModule gPIPNSSLog;
NS_IMPL_ISUPPORTS(CommonSocketControl, nsITLSSocketControl)
CommonSocketControl::CommonSocketControl(const nsCString& aHostName,
int32_t aPort, uint32_t aProviderFlags)
: mHostName(aHostName),
mPort(aPort),
mOriginAttributes(),
mCanceled(false),
mSessionCacheInfo(),
mHandshakeCompleted(false),
mJoined(false),
mSentClientCert(false),
mFailedVerification(false),
mSSLVersionUsed(nsITLSSocketControl::SSL_VERSION_UNKNOWN),
mProviderFlags(aProviderFlags),
mSecurityState(0),
mErrorCode(0),
mFailedCertChain(),
mServerCert(nullptr),
mSucceededCertChain(),
mCipherSuite(),
mKeaGroupName(),
mSignatureSchemeName(),
mProtocolVersion(),
mCertificateTransparencyStatus(0),
mIsAcceptedEch(),
mIsDelegatedCredential(),
mOverridableErrorCategory(),
mMadeOCSPRequests(false),
mUsedPrivateDNS(false),
mIsEV(),
mNPNCompleted(false),
mNegotiatedNPN(),
mResumed(false),
mIsBuiltCertChainRootBuiltInRoot(false),
mPeerId() {
#ifdef DEBUG
mOwningThread = PR_GetCurrentThread();
#endif
}
void CommonSocketControl::SetStatusErrorBits(
const nsCOMPtr<nsIX509Cert>& cert,
nsITransportSecurityInfo::OverridableErrorCategory
overridableErrorCategory) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
SetServerCert(cert, mozilla::psm::EVStatus::NotEV);
mOverridableErrorCategory = Some(overridableErrorCategory);
}
static void CreateCertChain(nsTArray<RefPtr<nsIX509Cert>>& aOutput,
nsTArray<nsTArray<uint8_t>>&& aCertList) {
nsTArray<nsTArray<uint8_t>> certList = std::move(aCertList);
aOutput.Clear();
for (auto& certBytes : certList) {
RefPtr<nsIX509Cert> cert = new nsNSSCertificate(std::move(certBytes));
aOutput.AppendElement(cert);
}
}
void CommonSocketControl::SetServerCert(
const nsCOMPtr<nsIX509Cert>& aServerCert,
mozilla::psm::EVStatus aEVStatus) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
mServerCert = aServerCert;
mIsEV = Some(aEVStatus == mozilla::psm::EVStatus::EV);
}
void CommonSocketControl::SetSucceededCertChain(
nsTArray<nsTArray<uint8_t>>&& aCertList) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
return CreateCertChain(mSucceededCertChain, std::move(aCertList));
}
void CommonSocketControl::SetFailedCertChain(
nsTArray<nsTArray<uint8_t>>&& aCertList) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
return CreateCertChain(mFailedCertChain, std::move(aCertList));
}
void CommonSocketControl::SetCanceled(PRErrorCode errorCode) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
MOZ_ASSERT(errorCode != 0);
if (errorCode == 0) {
errorCode = SEC_ERROR_LIBRARY_FAILURE;
}
mErrorCode = errorCode;
mCanceled = true;
}
// NB: GetErrorCode may be called before an error code is set (if ever). In that
// case, this returns 0, which is treated as a successful value.
int32_t CommonSocketControl::GetErrorCode() {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
// We're in an inconsistent state if we think we've been canceled but no error
// code was set or we haven't been canceled but an error code was set.
MOZ_ASSERT(
!((mCanceled && mErrorCode == 0) || (!mCanceled && mErrorCode != 0)));
if ((mCanceled && mErrorCode == 0) || (!mCanceled && mErrorCode != 0)) {
mCanceled = true;
mErrorCode = SEC_ERROR_LIBRARY_FAILURE;
}
return mErrorCode;
}
NS_IMETHODIMP
CommonSocketControl::ProxyStartSSL(void) { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
CommonSocketControl::StartTLS(void) { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
CommonSocketControl::SetNPNList(nsTArray<nsCString>& aNPNList) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetAlpnEarlySelection(nsACString& _retval) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetEarlyDataAccepted(bool* aEarlyDataAccepted) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::DriveHandshake(void) { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
CommonSocketControl::JoinConnection(const nsACString& npnProtocol,
const nsACString& hostname, int32_t port,
bool* _retval) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
nsresult rv = TestJoinConnection(npnProtocol, hostname, port, _retval);
if (NS_SUCCEEDED(rv) && *_retval) {
// All tests pass - this is joinable
mJoined = true;
}
return rv;
}
NS_IMETHODIMP
CommonSocketControl::TestJoinConnection(const nsACString& npnProtocol,
const nsACString& hostname,
int32_t port, bool* _retval) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
*_retval = false;
// Different ports may not be joined together
if (port != GetPort()) return NS_OK;
// Make sure NPN has been completed and matches requested npnProtocol
if (!mNPNCompleted || !mNegotiatedNPN.Equals(npnProtocol)) {
return NS_OK;
}
IsAcceptableForHost(hostname, _retval); // sets _retval
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::IsAcceptableForHost(const nsACString& hostname,
bool* _retval) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
NS_ENSURE_ARG(_retval);
*_retval = false;
// If this is the same hostname then the certicate status does not
// need to be considered. They are joinable.
if (hostname.Equals(GetHostName())) {
*_retval = true;
return NS_OK;
}
// Before checking the server certificate we need to make sure the
// handshake has completed.
if (!mHandshakeCompleted || !HasServerCert()) {
return NS_OK;
}
// Security checks can only be skipped when running xpcshell tests.
if (PR_GetEnv("XPCSHELL_TEST_PROFILE_DIR")) {
nsCOMPtr<nsICertOverrideService> overrideService =
do_GetService(NS_CERTOVERRIDE_CONTRACTID);
if (overrideService) {
bool securityCheckDisabled = false;
overrideService->GetSecurityCheckDisabled(&securityCheckDisabled);
if (securityCheckDisabled) {
*_retval = true;
return NS_OK;
}
}
}
// If the cert has error bits (e.g. it is untrusted) then do not join.
if (mOverridableErrorCategory.isSome()) {
return NS_OK;
}
// If the connection is using client certificates then do not join
// because the user decides on whether to send client certs to hosts on a
// per-domain basis.
if (mSentClientCert) return NS_OK;
// Ensure that the server certificate covers the hostname that would
// like to join this connection
nsCOMPtr<nsIX509Cert> cert(GetServerCert());
if (!cert) {
return NS_OK;
}
nsTArray<uint8_t> certDER;
if (NS_FAILED(cert->GetRawDER(certDER))) {
return NS_OK;
}
// An empty mSucceededCertChain means the server certificate verification
// failed before, so don't join in this case.
if (mSucceededCertChain.IsEmpty()) {
return NS_OK;
}
// See where CheckCertHostname() is called in
// CertVerifier::VerifySSLServerCert. We are doing the same hostname-specific
// checks here. If any hostname-specific checks are added to
// CertVerifier::VerifySSLServerCert we need to add them here too.
Input serverCertInput;
mozilla::pkix::Result rv =
serverCertInput.Init(certDER.Elements(), certDER.Length());
if (rv != Success) {
return NS_OK;
}
Input hostnameInput;
rv = hostnameInput.Init(
BitwiseCast<const uint8_t*, const char*>(hostname.BeginReading()),
hostname.Length());
if (rv != Success) {
return NS_OK;
}
rv = CheckCertHostname(serverCertInput, hostnameInput);
if (rv != Success) {
return NS_OK;
}
nsTArray<nsTArray<uint8_t>> rawDerCertList;
nsTArray<Span<const uint8_t>> derCertSpanList;
for (const auto& cert : mSucceededCertChain) {
rawDerCertList.EmplaceBack();
nsresult nsrv = cert->GetRawDER(rawDerCertList.LastElement());
if (NS_FAILED(nsrv)) {
return nsrv;
}
derCertSpanList.EmplaceBack(rawDerCertList.LastElement());
}
bool chainHasValidPins;
nsresult nsrv = mozilla::psm::PublicKeyPinningService::ChainHasValidPins(
derCertSpanList, PromiseFlatCString(hostname).BeginReading(), Now(),
mIsBuiltCertChainRootBuiltInRoot, chainHasValidPins, nullptr);
if (NS_FAILED(nsrv)) {
return NS_OK;
}
if (!chainHasValidPins) {
return NS_OK;
}
// All tests pass
*_retval = true;
return NS_OK;
}
void CommonSocketControl::RebuildCertificateInfoFromSSLTokenCache() {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
if (!mSessionCacheInfo) {
MOZ_LOG(
gPIPNSSLog, LogLevel::Debug,
("CommonSocketControl::RebuildCertificateInfoFromSSLTokenCache cannot "
"find cached info."));
return;
}
mozilla::net::SessionCacheInfo& info = *mSessionCacheInfo;
nsCOMPtr<nsIX509Cert> cert(
new nsNSSCertificate(std::move(info.mServerCertBytes)));
if (info.mOverridableErrorCategory ==
nsITransportSecurityInfo::OverridableErrorCategory::ERROR_UNSET) {
SetServerCert(cert, info.mEVStatus);
} else {
SetStatusErrorBits(cert, info.mOverridableErrorCategory);
}
SetCertificateTransparencyStatus(info.mCertificateTransparencyStatus);
if (info.mSucceededCertChainBytes) {
SetSucceededCertChain(std::move(*info.mSucceededCertChainBytes));
}
if (info.mIsBuiltCertChainRootBuiltInRoot) {
SetIsBuiltCertChainRootBuiltInRoot(*info.mIsBuiltCertChainRootBuiltInRoot);
}
if (info.mFailedCertChainBytes) {
SetFailedCertChain(std::move(*info.mFailedCertChainBytes));
}
}
NS_IMETHODIMP
CommonSocketControl::GetKEAUsed(int16_t* aKEAUsed) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetKEAKeyBits(uint32_t* aKEAKeyBits) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetProviderFlags(uint32_t* aProviderFlags) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
*aProviderFlags = mProviderFlags;
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::GetSSLVersionUsed(int16_t* aSSLVersionUsed) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
*aSSLVersionUsed = mSSLVersionUsed;
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::GetSSLVersionOffered(int16_t* aSSLVersionOffered) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetMACAlgorithmUsed(int16_t* aMACAlgorithmUsed) {
return NS_ERROR_NOT_IMPLEMENTED;
}
bool CommonSocketControl::GetDenyClientCert() { return true; }
void CommonSocketControl::SetDenyClientCert(bool aDenyClientCert) {}
NS_IMETHODIMP
CommonSocketControl::GetClientCertSent(bool* arg) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
*arg = mSentClientCert;
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::GetFailedVerification(bool* arg) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
*arg = mFailedVerification;
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::GetEsniTxt(nsACString& aEsniTxt) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::SetEsniTxt(const nsACString& aEsniTxt) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetEchConfig(nsACString& aEchConfig) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::SetEchConfig(const nsACString& aEchConfig) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::GetRetryEchConfig(nsACString& aEchConfig) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::SetHandshakeCallbackListener(
nsITlsHandshakeCallbackListener* callback) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
CommonSocketControl::DisableEarlyData(void) { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
CommonSocketControl::GetPeerId(nsACString& aResult) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
if (!mPeerId.IsEmpty()) {
aResult.Assign(mPeerId);
return NS_OK;
}
if (mProviderFlags &
nsISocketProvider::ANONYMOUS_CONNECT) { // See bug 466080
mPeerId.AppendLiteral("anon:");
}
if (mProviderFlags & nsISocketProvider::NO_PERMANENT_STORAGE) {
mPeerId.AppendLiteral("private:");
}
if (mProviderFlags & nsISocketProvider::BE_CONSERVATIVE) {
mPeerId.AppendLiteral("beConservative:");
}
mPeerId.Append(mHostName);
mPeerId.Append(':');
mPeerId.AppendInt(GetPort());
nsAutoCString suffix;
mOriginAttributes.CreateSuffix(suffix);
mPeerId.Append(suffix);
aResult.Assign(mPeerId);
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::GetSecurityInfo(nsITransportSecurityInfo** aSecurityInfo) {
COMMON_SOCKET_CONTROL_ASSERT_ON_OWNING_THREAD();
// Make sure peerId is set.
nsAutoCString unused;
nsresult rv = GetPeerId(unused);
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsITransportSecurityInfo> securityInfo(new TransportSecurityInfo(
mSecurityState, mErrorCode, mFailedCertChain.Clone(), mServerCert,
mSucceededCertChain.Clone(), mCipherSuite, mKeaGroupName,
mSignatureSchemeName, mProtocolVersion, mCertificateTransparencyStatus,
mIsAcceptedEch, mIsDelegatedCredential, mOverridableErrorCategory,
mMadeOCSPRequests, mUsedPrivateDNS, mIsEV, mNPNCompleted, mNegotiatedNPN,
mResumed, mIsBuiltCertChainRootBuiltInRoot, mPeerId));
securityInfo.forget(aSecurityInfo);
return NS_OK;
}
NS_IMETHODIMP
CommonSocketControl::AsyncGetSecurityInfo(JSContext* aCx,
mozilla::dom::Promise** aPromise) {
MOZ_RELEASE_ASSERT(NS_IsMainThread());
NS_ENSURE_ARG_POINTER(aCx);
NS_ENSURE_ARG_POINTER(aPromise);
nsIGlobalObject* globalObject = xpc::CurrentNativeGlobal(aCx);
if (!globalObject) {
return NS_ERROR_UNEXPECTED;
}
ErrorResult result;
RefPtr<mozilla::dom::Promise> promise =
mozilla::dom::Promise::Create(globalObject, result);
if (result.Failed()) {
return result.StealNSResult();
}
nsCOMPtr<nsIRunnable> runnable(NS_NewRunnableFunction(
"CommonSocketControl::AsyncGetSecurityInfo",
[promise, self = RefPtr{this}]() mutable {
nsCOMPtr<nsITransportSecurityInfo> securityInfo;
nsresult rv = self->GetSecurityInfo(getter_AddRefs(securityInfo));
nsCOMPtr<nsIRunnable> runnable(NS_NewRunnableFunction(
"CommonSocketControl::AsyncGetSecurityInfoResolve",
[rv, promise = std::move(promise),
securityInfo = std::move(securityInfo)]() {
if (NS_FAILED(rv)) {
promise->MaybeReject(rv);
} else {
promise->MaybeResolve(securityInfo);
}
}));
NS_DispatchToMainThread(runnable.forget());
}));
nsCOMPtr<nsIEventTarget> target(
do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID));
if (!target) {
return NS_ERROR_FAILURE;
}
nsresult rv = target->Dispatch(runnable, NS_DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
return rv;
}
promise.forget(aPromise);
return NS_OK;
}
|