1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/manager/ssl/src/nsNSSCallbacks.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,1323 @@ 1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- 1.5 + * 1.6 + * This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +#include "nsNSSCallbacks.h" 1.11 +#include "pkix/pkixtypes.h" 1.12 +#include "mozilla/Telemetry.h" 1.13 +#include "mozilla/TimeStamp.h" 1.14 +#include "nsNSSComponent.h" 1.15 +#include "nsNSSIOLayer.h" 1.16 +#include "nsIWebProgressListener.h" 1.17 +#include "nsProtectedAuthThread.h" 1.18 +#include "nsITokenDialogs.h" 1.19 +#include "nsIUploadChannel.h" 1.20 +#include "nsIPrompt.h" 1.21 +#include "nsProxyRelease.h" 1.22 +#include "PSMRunnable.h" 1.23 +#include "nsContentUtils.h" 1.24 +#include "nsIHttpChannelInternal.h" 1.25 +#include "nsISupportsPriority.h" 1.26 +#include "nsNetUtil.h" 1.27 +#include "SharedSSLState.h" 1.28 +#include "ssl.h" 1.29 +#include "sslproto.h" 1.30 + 1.31 +using namespace mozilla; 1.32 +using namespace mozilla::psm; 1.33 + 1.34 +#ifdef PR_LOGGING 1.35 +extern PRLogModuleInfo* gPIPNSSLog; 1.36 +#endif 1.37 + 1.38 +static void AccumulateCipherSuite(Telemetry::ID probe, 1.39 + const SSLChannelInfo& channelInfo); 1.40 + 1.41 +namespace { 1.42 + 1.43 +// Bits in bit mask for SSL_REASONS_FOR_NOT_FALSE_STARTING telemetry probe 1.44 +// These bits are numbered so that the least subtle issues have higher values. 1.45 +// This should make it easier for us to interpret the results. 1.46 +const uint32_t NPN_NOT_NEGOTIATED = 64; 1.47 +const uint32_t KEA_NOT_FORWARD_SECRET = 32; 1.48 +const uint32_t KEA_NOT_SAME_AS_EXPECTED = 16; 1.49 +const uint32_t KEA_NOT_ALLOWED = 8; 1.50 +const uint32_t POSSIBLE_VERSION_DOWNGRADE = 4; 1.51 +const uint32_t POSSIBLE_CIPHER_SUITE_DOWNGRADE = 2; 1.52 +const uint32_t KEA_NOT_SUPPORTED = 1; 1.53 + 1.54 +} 1.55 + 1.56 +class nsHTTPDownloadEvent : public nsRunnable { 1.57 +public: 1.58 + nsHTTPDownloadEvent(); 1.59 + ~nsHTTPDownloadEvent(); 1.60 + 1.61 + NS_IMETHOD Run(); 1.62 + 1.63 + nsNSSHttpRequestSession *mRequestSession; 1.64 + 1.65 + nsRefPtr<nsHTTPListener> mListener; 1.66 + bool mResponsibleForDoneSignal; 1.67 + TimeStamp mStartTime; 1.68 +}; 1.69 + 1.70 +nsHTTPDownloadEvent::nsHTTPDownloadEvent() 1.71 +:mResponsibleForDoneSignal(true) 1.72 +{ 1.73 +} 1.74 + 1.75 +nsHTTPDownloadEvent::~nsHTTPDownloadEvent() 1.76 +{ 1.77 + if (mResponsibleForDoneSignal && mListener) 1.78 + mListener->send_done_signal(); 1.79 + 1.80 + mRequestSession->Release(); 1.81 +} 1.82 + 1.83 +NS_IMETHODIMP 1.84 +nsHTTPDownloadEvent::Run() 1.85 +{ 1.86 + if (!mListener) 1.87 + return NS_OK; 1.88 + 1.89 + nsresult rv; 1.90 + 1.91 + nsCOMPtr<nsIIOService> ios = do_GetIOService(); 1.92 + NS_ENSURE_STATE(ios); 1.93 + 1.94 + nsCOMPtr<nsIChannel> chan; 1.95 + ios->NewChannel(mRequestSession->mURL, nullptr, nullptr, getter_AddRefs(chan)); 1.96 + NS_ENSURE_STATE(chan); 1.97 + 1.98 + // Security operations scheduled through normal HTTP channels are given 1.99 + // high priority to accommodate real time OCSP transactions. Background CRL 1.100 + // fetches happen through a different path (CRLDownloadEvent). 1.101 + nsCOMPtr<nsISupportsPriority> priorityChannel = do_QueryInterface(chan); 1.102 + if (priorityChannel) 1.103 + priorityChannel->AdjustPriority(nsISupportsPriority::PRIORITY_HIGHEST); 1.104 + 1.105 + chan->SetLoadFlags(nsIRequest::LOAD_ANONYMOUS); 1.106 + 1.107 + // Create a loadgroup for this new channel. This way if the channel 1.108 + // is redirected, we'll have a way to cancel the resulting channel. 1.109 + nsCOMPtr<nsILoadGroup> lg = do_CreateInstance(NS_LOADGROUP_CONTRACTID); 1.110 + chan->SetLoadGroup(lg); 1.111 + 1.112 + if (mRequestSession->mHasPostData) 1.113 + { 1.114 + nsCOMPtr<nsIInputStream> uploadStream; 1.115 + rv = NS_NewPostDataStream(getter_AddRefs(uploadStream), 1.116 + false, 1.117 + mRequestSession->mPostData); 1.118 + NS_ENSURE_SUCCESS(rv, rv); 1.119 + 1.120 + nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(chan)); 1.121 + NS_ENSURE_STATE(uploadChannel); 1.122 + 1.123 + rv = uploadChannel->SetUploadStream(uploadStream, 1.124 + mRequestSession->mPostContentType, 1.125 + -1); 1.126 + NS_ENSURE_SUCCESS(rv, rv); 1.127 + } 1.128 + 1.129 + // Do not use SPDY for internal security operations. It could result 1.130 + // in the silent upgrade to ssl, which in turn could require an SSL 1.131 + // operation to fufill something like a CRL fetch, which is an 1.132 + // endless loop. 1.133 + nsCOMPtr<nsIHttpChannelInternal> internalChannel = do_QueryInterface(chan); 1.134 + if (internalChannel) { 1.135 + rv = internalChannel->SetAllowSpdy(false); 1.136 + NS_ENSURE_SUCCESS(rv, rv); 1.137 + } 1.138 + 1.139 + nsCOMPtr<nsIHttpChannel> hchan = do_QueryInterface(chan); 1.140 + NS_ENSURE_STATE(hchan); 1.141 + 1.142 + rv = hchan->SetRequestMethod(mRequestSession->mRequestMethod); 1.143 + NS_ENSURE_SUCCESS(rv, rv); 1.144 + 1.145 + mResponsibleForDoneSignal = false; 1.146 + mListener->mResponsibleForDoneSignal = true; 1.147 + 1.148 + mListener->mLoadGroup = lg.get(); 1.149 + NS_ADDREF(mListener->mLoadGroup); 1.150 + mListener->mLoadGroupOwnerThread = PR_GetCurrentThread(); 1.151 + 1.152 + rv = NS_NewStreamLoader(getter_AddRefs(mListener->mLoader), 1.153 + mListener); 1.154 + 1.155 + if (NS_SUCCEEDED(rv)) { 1.156 + mStartTime = TimeStamp::Now(); 1.157 + rv = hchan->AsyncOpen(mListener->mLoader, nullptr); 1.158 + } 1.159 + 1.160 + if (NS_FAILED(rv)) { 1.161 + mListener->mResponsibleForDoneSignal = false; 1.162 + mResponsibleForDoneSignal = true; 1.163 + 1.164 + NS_RELEASE(mListener->mLoadGroup); 1.165 + mListener->mLoadGroup = nullptr; 1.166 + mListener->mLoadGroupOwnerThread = nullptr; 1.167 + } 1.168 + 1.169 + return NS_OK; 1.170 +} 1.171 + 1.172 +struct nsCancelHTTPDownloadEvent : nsRunnable { 1.173 + nsRefPtr<nsHTTPListener> mListener; 1.174 + 1.175 + NS_IMETHOD Run() { 1.176 + mListener->FreeLoadGroup(true); 1.177 + mListener = nullptr; 1.178 + return NS_OK; 1.179 + } 1.180 +}; 1.181 + 1.182 +SECStatus nsNSSHttpServerSession::createSessionFcn(const char *host, 1.183 + uint16_t portnum, 1.184 + SEC_HTTP_SERVER_SESSION *pSession) 1.185 +{ 1.186 + if (!host || !pSession) 1.187 + return SECFailure; 1.188 + 1.189 + nsNSSHttpServerSession *hss = new nsNSSHttpServerSession; 1.190 + if (!hss) 1.191 + return SECFailure; 1.192 + 1.193 + hss->mHost = host; 1.194 + hss->mPort = portnum; 1.195 + 1.196 + *pSession = hss; 1.197 + return SECSuccess; 1.198 +} 1.199 + 1.200 +SECStatus nsNSSHttpRequestSession::createFcn(SEC_HTTP_SERVER_SESSION session, 1.201 + const char *http_protocol_variant, 1.202 + const char *path_and_query_string, 1.203 + const char *http_request_method, 1.204 + const PRIntervalTime timeout, 1.205 + SEC_HTTP_REQUEST_SESSION *pRequest) 1.206 +{ 1.207 + if (!session || !http_protocol_variant || !path_and_query_string || 1.208 + !http_request_method || !pRequest) 1.209 + return SECFailure; 1.210 + 1.211 + nsNSSHttpServerSession* hss = static_cast<nsNSSHttpServerSession*>(session); 1.212 + if (!hss) 1.213 + return SECFailure; 1.214 + 1.215 + nsNSSHttpRequestSession *rs = new nsNSSHttpRequestSession; 1.216 + if (!rs) 1.217 + return SECFailure; 1.218 + 1.219 + rs->mTimeoutInterval = timeout; 1.220 + 1.221 + // Use a maximum timeout value of 10 seconds because of bug 404059. 1.222 + // FIXME: Use a better approach once 406120 is ready. 1.223 + uint32_t maxBug404059Timeout = PR_TicksPerSecond() * 10; 1.224 + if (timeout > maxBug404059Timeout) { 1.225 + rs->mTimeoutInterval = maxBug404059Timeout; 1.226 + } 1.227 + 1.228 + rs->mURL.Assign(http_protocol_variant); 1.229 + rs->mURL.AppendLiteral("://"); 1.230 + rs->mURL.Append(hss->mHost); 1.231 + rs->mURL.AppendLiteral(":"); 1.232 + rs->mURL.AppendInt(hss->mPort); 1.233 + rs->mURL.Append(path_and_query_string); 1.234 + 1.235 + rs->mRequestMethod = http_request_method; 1.236 + 1.237 + *pRequest = (void*)rs; 1.238 + return SECSuccess; 1.239 +} 1.240 + 1.241 +SECStatus nsNSSHttpRequestSession::setPostDataFcn(const char *http_data, 1.242 + const uint32_t http_data_len, 1.243 + const char *http_content_type) 1.244 +{ 1.245 + mHasPostData = true; 1.246 + mPostData.Assign(http_data, http_data_len); 1.247 + mPostContentType.Assign(http_content_type); 1.248 + 1.249 + return SECSuccess; 1.250 +} 1.251 + 1.252 +SECStatus nsNSSHttpRequestSession::addHeaderFcn(const char *http_header_name, 1.253 + const char *http_header_value) 1.254 +{ 1.255 + return SECFailure; // not yet implemented 1.256 + 1.257 + // All http code needs to be postponed to the UI thread. 1.258 + // Once this gets implemented, we need to add a string list member to 1.259 + // nsNSSHttpRequestSession and queue up the headers, 1.260 + // so they can be added in HandleHTTPDownloadPLEvent. 1.261 + // 1.262 + // The header will need to be set using 1.263 + // mHttpChannel->SetRequestHeader(nsDependentCString(http_header_name), 1.264 + // nsDependentCString(http_header_value), 1.265 + // false))); 1.266 +} 1.267 + 1.268 +SECStatus nsNSSHttpRequestSession::trySendAndReceiveFcn(PRPollDesc **pPollDesc, 1.269 + uint16_t *http_response_code, 1.270 + const char **http_response_content_type, 1.271 + const char **http_response_headers, 1.272 + const char **http_response_data, 1.273 + uint32_t *http_response_data_len) 1.274 +{ 1.275 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.276 + ("nsNSSHttpRequestSession::trySendAndReceiveFcn to %s\n", mURL.get())); 1.277 + 1.278 + bool onSTSThread; 1.279 + nsresult nrv; 1.280 + nsCOMPtr<nsIEventTarget> sts 1.281 + = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &nrv); 1.282 + if (NS_FAILED(nrv)) { 1.283 + NS_ERROR("Could not get STS service"); 1.284 + PR_SetError(PR_INVALID_STATE_ERROR, 0); 1.285 + return SECFailure; 1.286 + } 1.287 + 1.288 + nrv = sts->IsOnCurrentThread(&onSTSThread); 1.289 + if (NS_FAILED(nrv)) { 1.290 + NS_ERROR("IsOnCurrentThread failed"); 1.291 + PR_SetError(PR_INVALID_STATE_ERROR, 0); 1.292 + return SECFailure; 1.293 + } 1.294 + 1.295 + if (onSTSThread) { 1.296 + NS_ERROR("nsNSSHttpRequestSession::trySendAndReceiveFcn called on socket " 1.297 + "thread; this will not work."); 1.298 + PR_SetError(PR_INVALID_STATE_ERROR, 0); 1.299 + return SECFailure; 1.300 + } 1.301 + 1.302 + const int max_retries = 2; 1.303 + int retry_count = 0; 1.304 + bool retryable_error = false; 1.305 + SECStatus result_sec_status = SECFailure; 1.306 + 1.307 + do 1.308 + { 1.309 + if (retry_count > 0) 1.310 + { 1.311 + if (retryable_error) 1.312 + { 1.313 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.314 + ("nsNSSHttpRequestSession::trySendAndReceiveFcn - sleeping and retrying: %d of %d\n", 1.315 + retry_count, max_retries)); 1.316 + } 1.317 + 1.318 + PR_Sleep( PR_MillisecondsToInterval(300) * retry_count ); 1.319 + } 1.320 + 1.321 + ++retry_count; 1.322 + retryable_error = false; 1.323 + 1.324 + result_sec_status = 1.325 + internal_send_receive_attempt(retryable_error, pPollDesc, http_response_code, 1.326 + http_response_content_type, http_response_headers, 1.327 + http_response_data, http_response_data_len); 1.328 + } 1.329 + while (retryable_error && 1.330 + retry_count < max_retries); 1.331 + 1.332 +#ifdef PR_LOGGING 1.333 + if (retry_count > 1) 1.334 + { 1.335 + if (retryable_error) 1.336 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.337 + ("nsNSSHttpRequestSession::trySendAndReceiveFcn - still failing, giving up...\n")); 1.338 + else 1.339 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.340 + ("nsNSSHttpRequestSession::trySendAndReceiveFcn - success at attempt %d\n", 1.341 + retry_count)); 1.342 + } 1.343 +#endif 1.344 + 1.345 + return result_sec_status; 1.346 +} 1.347 + 1.348 +void 1.349 +nsNSSHttpRequestSession::AddRef() 1.350 +{ 1.351 + ++mRefCount; 1.352 +} 1.353 + 1.354 +void 1.355 +nsNSSHttpRequestSession::Release() 1.356 +{ 1.357 + int32_t newRefCount = --mRefCount; 1.358 + if (!newRefCount) { 1.359 + delete this; 1.360 + } 1.361 +} 1.362 + 1.363 +SECStatus 1.364 +nsNSSHttpRequestSession::internal_send_receive_attempt(bool &retryable_error, 1.365 + PRPollDesc **pPollDesc, 1.366 + uint16_t *http_response_code, 1.367 + const char **http_response_content_type, 1.368 + const char **http_response_headers, 1.369 + const char **http_response_data, 1.370 + uint32_t *http_response_data_len) 1.371 +{ 1.372 + if (pPollDesc) *pPollDesc = nullptr; 1.373 + if (http_response_code) *http_response_code = 0; 1.374 + if (http_response_content_type) *http_response_content_type = 0; 1.375 + if (http_response_headers) *http_response_headers = 0; 1.376 + if (http_response_data) *http_response_data = 0; 1.377 + 1.378 + uint32_t acceptableResultSize = 0; 1.379 + 1.380 + if (http_response_data_len) 1.381 + { 1.382 + acceptableResultSize = *http_response_data_len; 1.383 + *http_response_data_len = 0; 1.384 + } 1.385 + 1.386 + if (!mListener) 1.387 + return SECFailure; 1.388 + 1.389 + Mutex& waitLock = mListener->mLock; 1.390 + CondVar& waitCondition = mListener->mCondition; 1.391 + volatile bool &waitFlag = mListener->mWaitFlag; 1.392 + waitFlag = true; 1.393 + 1.394 + RefPtr<nsHTTPDownloadEvent> event(new nsHTTPDownloadEvent); 1.395 + if (!event) 1.396 + return SECFailure; 1.397 + 1.398 + event->mListener = mListener; 1.399 + this->AddRef(); 1.400 + event->mRequestSession = this; 1.401 + 1.402 + nsresult rv = NS_DispatchToMainThread(event); 1.403 + if (NS_FAILED(rv)) 1.404 + { 1.405 + event->mResponsibleForDoneSignal = false; 1.406 + return SECFailure; 1.407 + } 1.408 + 1.409 + bool request_canceled = false; 1.410 + 1.411 + { 1.412 + MutexAutoLock locker(waitLock); 1.413 + 1.414 + const PRIntervalTime start_time = PR_IntervalNow(); 1.415 + PRIntervalTime wait_interval; 1.416 + 1.417 + bool running_on_main_thread = NS_IsMainThread(); 1.418 + if (running_on_main_thread) 1.419 + { 1.420 + // The result of running this on the main thread 1.421 + // is a series of small timeouts mixed with spinning the 1.422 + // event loop - this is always dangerous as there is so much main 1.423 + // thread code that does not expect to be called re-entrantly. Your 1.424 + // app really shouldn't do that. 1.425 + NS_WARNING("Security network blocking I/O on Main Thread"); 1.426 + 1.427 + // let's process events quickly 1.428 + wait_interval = PR_MicrosecondsToInterval(50); 1.429 + } 1.430 + else 1.431 + { 1.432 + // On a secondary thread, it's fine to wait some more for 1.433 + // for the condition variable. 1.434 + wait_interval = PR_MillisecondsToInterval(250); 1.435 + } 1.436 + 1.437 + while (waitFlag) 1.438 + { 1.439 + if (running_on_main_thread) 1.440 + { 1.441 + // Networking runs on the main thread, which we happen to block here. 1.442 + // Processing events will allow the OCSP networking to run while we 1.443 + // are waiting. Thanks a lot to Darin Fisher for rewriting the 1.444 + // thread manager. Thanks a lot to Christian Biesinger who 1.445 + // made me aware of this possibility. (kaie) 1.446 + 1.447 + MutexAutoUnlock unlock(waitLock); 1.448 + NS_ProcessNextEvent(nullptr); 1.449 + } 1.450 + 1.451 + waitCondition.Wait(wait_interval); 1.452 + 1.453 + if (!waitFlag) 1.454 + break; 1.455 + 1.456 + if (!request_canceled) 1.457 + { 1.458 + bool timeout = 1.459 + (PRIntervalTime)(PR_IntervalNow() - start_time) > mTimeoutInterval; 1.460 + 1.461 + if (timeout) 1.462 + { 1.463 + request_canceled = true; 1.464 + 1.465 + RefPtr<nsCancelHTTPDownloadEvent> cancelevent( 1.466 + new nsCancelHTTPDownloadEvent); 1.467 + cancelevent->mListener = mListener; 1.468 + rv = NS_DispatchToMainThread(cancelevent); 1.469 + if (NS_FAILED(rv)) { 1.470 + NS_WARNING("cannot post cancel event"); 1.471 + } 1.472 + break; 1.473 + } 1.474 + } 1.475 + } 1.476 + } 1.477 + 1.478 + if (!event->mStartTime.IsNull()) { 1.479 + if (request_canceled) { 1.480 + Telemetry::Accumulate(Telemetry::CERT_VALIDATION_HTTP_REQUEST_RESULT, 0); 1.481 + Telemetry::AccumulateTimeDelta( 1.482 + Telemetry::CERT_VALIDATION_HTTP_REQUEST_CANCELED_TIME, 1.483 + event->mStartTime, TimeStamp::Now()); 1.484 + } 1.485 + else if (NS_SUCCEEDED(mListener->mResultCode) && 1.486 + mListener->mHttpResponseCode == 200) { 1.487 + Telemetry::Accumulate(Telemetry::CERT_VALIDATION_HTTP_REQUEST_RESULT, 1); 1.488 + Telemetry::AccumulateTimeDelta( 1.489 + Telemetry::CERT_VALIDATION_HTTP_REQUEST_SUCCEEDED_TIME, 1.490 + event->mStartTime, TimeStamp::Now()); 1.491 + } 1.492 + else { 1.493 + Telemetry::Accumulate(Telemetry::CERT_VALIDATION_HTTP_REQUEST_RESULT, 2); 1.494 + Telemetry::AccumulateTimeDelta( 1.495 + Telemetry::CERT_VALIDATION_HTTP_REQUEST_FAILED_TIME, 1.496 + event->mStartTime, TimeStamp::Now()); 1.497 + } 1.498 + } 1.499 + else { 1.500 + Telemetry::Accumulate(Telemetry::CERT_VALIDATION_HTTP_REQUEST_RESULT, 3); 1.501 + } 1.502 + 1.503 + if (request_canceled) 1.504 + return SECFailure; 1.505 + 1.506 + if (NS_FAILED(mListener->mResultCode)) 1.507 + { 1.508 + if (mListener->mResultCode == NS_ERROR_CONNECTION_REFUSED 1.509 + || 1.510 + mListener->mResultCode == NS_ERROR_NET_RESET) 1.511 + { 1.512 + retryable_error = true; 1.513 + } 1.514 + return SECFailure; 1.515 + } 1.516 + 1.517 + if (http_response_code) 1.518 + *http_response_code = mListener->mHttpResponseCode; 1.519 + 1.520 + if (mListener->mHttpRequestSucceeded && http_response_data && http_response_data_len) { 1.521 + 1.522 + *http_response_data_len = mListener->mResultLen; 1.523 + 1.524 + // acceptableResultSize == 0 means: any size is acceptable 1.525 + if (acceptableResultSize != 0 1.526 + && 1.527 + acceptableResultSize < mListener->mResultLen) 1.528 + { 1.529 + return SECFailure; 1.530 + } 1.531 + 1.532 + // return data by reference, result data will be valid 1.533 + // until "this" gets destroyed by NSS 1.534 + *http_response_data = (const char*)mListener->mResultData; 1.535 + } 1.536 + 1.537 + if (mListener->mHttpRequestSucceeded && http_response_content_type) { 1.538 + if (mListener->mHttpResponseContentType.Length()) { 1.539 + *http_response_content_type = mListener->mHttpResponseContentType.get(); 1.540 + } 1.541 + } 1.542 + 1.543 + return SECSuccess; 1.544 +} 1.545 + 1.546 +SECStatus nsNSSHttpRequestSession::cancelFcn() 1.547 +{ 1.548 + // As of today, only the blocking variant of the http interface 1.549 + // has been implemented. Implementing cancelFcn will be necessary 1.550 + // as soon as we implement the nonblocking variant. 1.551 + return SECSuccess; 1.552 +} 1.553 + 1.554 +SECStatus nsNSSHttpRequestSession::freeFcn() 1.555 +{ 1.556 + Release(); 1.557 + return SECSuccess; 1.558 +} 1.559 + 1.560 +nsNSSHttpRequestSession::nsNSSHttpRequestSession() 1.561 +: mRefCount(1), 1.562 + mHasPostData(false), 1.563 + mTimeoutInterval(0), 1.564 + mListener(new nsHTTPListener) 1.565 +{ 1.566 +} 1.567 + 1.568 +nsNSSHttpRequestSession::~nsNSSHttpRequestSession() 1.569 +{ 1.570 +} 1.571 + 1.572 +SEC_HttpClientFcn nsNSSHttpInterface::sNSSInterfaceTable; 1.573 + 1.574 +void nsNSSHttpInterface::initTable() 1.575 +{ 1.576 + sNSSInterfaceTable.version = 1; 1.577 + SEC_HttpClientFcnV1 &v1 = sNSSInterfaceTable.fcnTable.ftable1; 1.578 + v1.createSessionFcn = createSessionFcn; 1.579 + v1.keepAliveSessionFcn = keepAliveFcn; 1.580 + v1.freeSessionFcn = freeSessionFcn; 1.581 + v1.createFcn = createFcn; 1.582 + v1.setPostDataFcn = setPostDataFcn; 1.583 + v1.addHeaderFcn = addHeaderFcn; 1.584 + v1.trySendAndReceiveFcn = trySendAndReceiveFcn; 1.585 + v1.cancelFcn = cancelFcn; 1.586 + v1.freeFcn = freeFcn; 1.587 +} 1.588 + 1.589 +void nsNSSHttpInterface::registerHttpClient() 1.590 +{ 1.591 + SEC_RegisterDefaultHttpClient(&sNSSInterfaceTable); 1.592 +} 1.593 + 1.594 +void nsNSSHttpInterface::unregisterHttpClient() 1.595 +{ 1.596 + SEC_RegisterDefaultHttpClient(nullptr); 1.597 +} 1.598 + 1.599 +nsHTTPListener::nsHTTPListener() 1.600 +: mResultData(nullptr), 1.601 + mResultLen(0), 1.602 + mLock("nsHTTPListener.mLock"), 1.603 + mCondition(mLock, "nsHTTPListener.mCondition"), 1.604 + mWaitFlag(true), 1.605 + mResponsibleForDoneSignal(false), 1.606 + mLoadGroup(nullptr), 1.607 + mLoadGroupOwnerThread(nullptr) 1.608 +{ 1.609 +} 1.610 + 1.611 +nsHTTPListener::~nsHTTPListener() 1.612 +{ 1.613 + if (mResponsibleForDoneSignal) 1.614 + send_done_signal(); 1.615 + 1.616 + if (mResultData) { 1.617 + NS_Free(const_cast<uint8_t *>(mResultData)); 1.618 + } 1.619 + 1.620 + if (mLoader) { 1.621 + nsCOMPtr<nsIThread> mainThread(do_GetMainThread()); 1.622 + NS_ProxyRelease(mainThread, mLoader); 1.623 + } 1.624 +} 1.625 + 1.626 +NS_IMPL_ISUPPORTS(nsHTTPListener, nsIStreamLoaderObserver) 1.627 + 1.628 +void 1.629 +nsHTTPListener::FreeLoadGroup(bool aCancelLoad) 1.630 +{ 1.631 + nsILoadGroup *lg = nullptr; 1.632 + 1.633 + MutexAutoLock locker(mLock); 1.634 + 1.635 + if (mLoadGroup) { 1.636 + if (mLoadGroupOwnerThread != PR_GetCurrentThread()) { 1.637 + NS_ASSERTION(false, 1.638 + "attempt to access nsHTTPDownloadEvent::mLoadGroup on multiple threads, leaking it!"); 1.639 + } 1.640 + else { 1.641 + lg = mLoadGroup; 1.642 + mLoadGroup = nullptr; 1.643 + } 1.644 + } 1.645 + 1.646 + if (lg) { 1.647 + if (aCancelLoad) { 1.648 + lg->Cancel(NS_ERROR_ABORT); 1.649 + } 1.650 + NS_RELEASE(lg); 1.651 + } 1.652 +} 1.653 + 1.654 +NS_IMETHODIMP 1.655 +nsHTTPListener::OnStreamComplete(nsIStreamLoader* aLoader, 1.656 + nsISupports* aContext, 1.657 + nsresult aStatus, 1.658 + uint32_t stringLen, 1.659 + const uint8_t* string) 1.660 +{ 1.661 + mResultCode = aStatus; 1.662 + 1.663 + FreeLoadGroup(false); 1.664 + 1.665 + nsCOMPtr<nsIRequest> req; 1.666 + nsCOMPtr<nsIHttpChannel> hchan; 1.667 + 1.668 + nsresult rv = aLoader->GetRequest(getter_AddRefs(req)); 1.669 + 1.670 +#ifdef PR_LOGGING 1.671 + if (NS_FAILED(aStatus)) 1.672 + { 1.673 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.674 + ("nsHTTPListener::OnStreamComplete status failed %d", aStatus)); 1.675 + } 1.676 +#endif 1.677 + 1.678 + if (NS_SUCCEEDED(rv)) 1.679 + hchan = do_QueryInterface(req, &rv); 1.680 + 1.681 + if (NS_SUCCEEDED(rv)) 1.682 + { 1.683 + rv = hchan->GetRequestSucceeded(&mHttpRequestSucceeded); 1.684 + if (NS_FAILED(rv)) 1.685 + mHttpRequestSucceeded = false; 1.686 + 1.687 + mResultLen = stringLen; 1.688 + mResultData = string; // take ownership of allocation 1.689 + aStatus = NS_SUCCESS_ADOPTED_DATA; 1.690 + 1.691 + unsigned int rcode; 1.692 + rv = hchan->GetResponseStatus(&rcode); 1.693 + if (NS_FAILED(rv)) 1.694 + mHttpResponseCode = 500; 1.695 + else 1.696 + mHttpResponseCode = rcode; 1.697 + 1.698 + hchan->GetResponseHeader(NS_LITERAL_CSTRING("Content-Type"), 1.699 + mHttpResponseContentType); 1.700 + } 1.701 + 1.702 + if (mResponsibleForDoneSignal) 1.703 + send_done_signal(); 1.704 + 1.705 + return aStatus; 1.706 +} 1.707 + 1.708 +void nsHTTPListener::send_done_signal() 1.709 +{ 1.710 + mResponsibleForDoneSignal = false; 1.711 + 1.712 + { 1.713 + MutexAutoLock locker(mLock); 1.714 + mWaitFlag = false; 1.715 + mCondition.NotifyAll(); 1.716 + } 1.717 +} 1.718 + 1.719 +static char* 1.720 +ShowProtectedAuthPrompt(PK11SlotInfo* slot, nsIInterfaceRequestor *ir) 1.721 +{ 1.722 + if (!NS_IsMainThread()) { 1.723 + NS_ERROR("ShowProtectedAuthPrompt called off the main thread"); 1.724 + return nullptr; 1.725 + } 1.726 + 1.727 + char* protAuthRetVal = nullptr; 1.728 + 1.729 + // Get protected auth dialogs 1.730 + nsITokenDialogs* dialogs = 0; 1.731 + nsresult nsrv = getNSSDialogs((void**)&dialogs, 1.732 + NS_GET_IID(nsITokenDialogs), 1.733 + NS_TOKENDIALOGS_CONTRACTID); 1.734 + if (NS_SUCCEEDED(nsrv)) 1.735 + { 1.736 + nsProtectedAuthThread* protectedAuthRunnable = new nsProtectedAuthThread(); 1.737 + if (protectedAuthRunnable) 1.738 + { 1.739 + NS_ADDREF(protectedAuthRunnable); 1.740 + 1.741 + protectedAuthRunnable->SetParams(slot); 1.742 + 1.743 + nsCOMPtr<nsIProtectedAuthThread> runnable = do_QueryInterface(protectedAuthRunnable); 1.744 + if (runnable) 1.745 + { 1.746 + nsrv = dialogs->DisplayProtectedAuth(ir, runnable); 1.747 + 1.748 + // We call join on the thread, 1.749 + // so we can be sure that no simultaneous access will happen. 1.750 + protectedAuthRunnable->Join(); 1.751 + 1.752 + if (NS_SUCCEEDED(nsrv)) 1.753 + { 1.754 + SECStatus rv = protectedAuthRunnable->GetResult(); 1.755 + switch (rv) 1.756 + { 1.757 + case SECSuccess: 1.758 + protAuthRetVal = ToNewCString(nsDependentCString(PK11_PW_AUTHENTICATED)); 1.759 + break; 1.760 + case SECWouldBlock: 1.761 + protAuthRetVal = ToNewCString(nsDependentCString(PK11_PW_RETRY)); 1.762 + break; 1.763 + default: 1.764 + protAuthRetVal = nullptr; 1.765 + break; 1.766 + 1.767 + } 1.768 + } 1.769 + } 1.770 + 1.771 + NS_RELEASE(protectedAuthRunnable); 1.772 + } 1.773 + 1.774 + NS_RELEASE(dialogs); 1.775 + } 1.776 + 1.777 + return protAuthRetVal; 1.778 +} 1.779 + 1.780 +class PK11PasswordPromptRunnable : public SyncRunnableBase 1.781 +{ 1.782 +public: 1.783 + PK11PasswordPromptRunnable(PK11SlotInfo* slot, 1.784 + nsIInterfaceRequestor* ir) 1.785 + : mResult(nullptr), 1.786 + mSlot(slot), 1.787 + mIR(ir) 1.788 + { 1.789 + } 1.790 + char * mResult; // out 1.791 + virtual void RunOnTargetThread(); 1.792 +private: 1.793 + PK11SlotInfo* const mSlot; // in 1.794 + nsIInterfaceRequestor* const mIR; // in 1.795 +}; 1.796 + 1.797 +void PK11PasswordPromptRunnable::RunOnTargetThread() 1.798 +{ 1.799 + static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); 1.800 + 1.801 + nsNSSShutDownPreventionLock locker; 1.802 + nsresult rv = NS_OK; 1.803 + char16_t *password = nullptr; 1.804 + bool value = false; 1.805 + nsCOMPtr<nsIPrompt> prompt; 1.806 + 1.807 + /* TODO: Retry should generate a different dialog message */ 1.808 +/* 1.809 + if (retry) 1.810 + return nullptr; 1.811 +*/ 1.812 + 1.813 + if (!mIR) 1.814 + { 1.815 + nsNSSComponent::GetNewPrompter(getter_AddRefs(prompt)); 1.816 + } 1.817 + else 1.818 + { 1.819 + prompt = do_GetInterface(mIR); 1.820 + NS_ASSERTION(prompt, "callbacks does not implement nsIPrompt"); 1.821 + } 1.822 + 1.823 + if (!prompt) 1.824 + return; 1.825 + 1.826 + if (PK11_ProtectedAuthenticationPath(mSlot)) { 1.827 + mResult = ShowProtectedAuthPrompt(mSlot, mIR); 1.828 + return; 1.829 + } 1.830 + 1.831 + nsAutoString promptString; 1.832 + nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv)); 1.833 + 1.834 + if (NS_FAILED(rv)) 1.835 + return; 1.836 + 1.837 + const char16_t* formatStrings[1] = { 1.838 + ToNewUnicode(NS_ConvertUTF8toUTF16(PK11_GetTokenName(mSlot))) 1.839 + }; 1.840 + rv = nssComponent->PIPBundleFormatStringFromName("CertPassPrompt", 1.841 + formatStrings, 1, 1.842 + promptString); 1.843 + nsMemory::Free(const_cast<char16_t*>(formatStrings[0])); 1.844 + 1.845 + if (NS_FAILED(rv)) 1.846 + return; 1.847 + 1.848 + { 1.849 + nsPSMUITracker tracker; 1.850 + if (tracker.isUIForbidden()) { 1.851 + rv = NS_ERROR_NOT_AVAILABLE; 1.852 + } 1.853 + else { 1.854 + // Although the exact value is ignored, we must not pass invalid 1.855 + // bool values through XPConnect. 1.856 + bool checkState = false; 1.857 + rv = prompt->PromptPassword(nullptr, promptString.get(), 1.858 + &password, nullptr, &checkState, &value); 1.859 + } 1.860 + } 1.861 + 1.862 + if (NS_SUCCEEDED(rv) && value) { 1.863 + mResult = ToNewUTF8String(nsDependentString(password)); 1.864 + NS_Free(password); 1.865 + } 1.866 +} 1.867 + 1.868 +char* 1.869 +PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg) 1.870 +{ 1.871 + RefPtr<PK11PasswordPromptRunnable> runnable( 1.872 + new PK11PasswordPromptRunnable(slot, 1.873 + static_cast<nsIInterfaceRequestor*>(arg))); 1.874 + runnable->DispatchToMainThreadAndWait(); 1.875 + return runnable->mResult; 1.876 +} 1.877 + 1.878 +// call with shutdown prevention lock held 1.879 +static void 1.880 +PreliminaryHandshakeDone(PRFileDesc* fd) 1.881 +{ 1.882 + nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret; 1.883 + if (!infoObject) 1.884 + return; 1.885 + 1.886 + if (infoObject->IsPreliminaryHandshakeDone()) 1.887 + return; 1.888 + 1.889 + infoObject->SetPreliminaryHandshakeDone(); 1.890 + 1.891 + SSLChannelInfo channelInfo; 1.892 + if (SSL_GetChannelInfo(fd, &channelInfo, sizeof(channelInfo)) == SECSuccess) { 1.893 + infoObject->SetSSLVersionUsed(channelInfo.protocolVersion); 1.894 + } 1.895 + 1.896 + // Get the NPN value. 1.897 + SSLNextProtoState state; 1.898 + unsigned char npnbuf[256]; 1.899 + unsigned int npnlen; 1.900 + 1.901 + if (SSL_GetNextProto(fd, &state, npnbuf, &npnlen, 256) == SECSuccess) { 1.902 + if (state == SSL_NEXT_PROTO_NEGOTIATED || 1.903 + state == SSL_NEXT_PROTO_SELECTED) { 1.904 + infoObject->SetNegotiatedNPN(reinterpret_cast<char *>(npnbuf), npnlen); 1.905 + } 1.906 + else { 1.907 + infoObject->SetNegotiatedNPN(nullptr, 0); 1.908 + } 1.909 + mozilla::Telemetry::Accumulate(Telemetry::SSL_NPN_TYPE, state); 1.910 + } 1.911 + else { 1.912 + infoObject->SetNegotiatedNPN(nullptr, 0); 1.913 + } 1.914 +} 1.915 + 1.916 +SECStatus 1.917 +CanFalseStartCallback(PRFileDesc* fd, void* client_data, PRBool *canFalseStart) 1.918 +{ 1.919 + *canFalseStart = false; 1.920 + 1.921 + nsNSSShutDownPreventionLock locker; 1.922 + 1.923 + nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret; 1.924 + if (!infoObject) { 1.925 + PR_SetError(PR_INVALID_STATE_ERROR, 0); 1.926 + return SECFailure; 1.927 + } 1.928 + 1.929 + infoObject->SetFalseStartCallbackCalled(); 1.930 + 1.931 + if (infoObject->isAlreadyShutDown()) { 1.932 + MOZ_CRASH("SSL socket used after NSS shut down"); 1.933 + PR_SetError(PR_INVALID_STATE_ERROR, 0); 1.934 + return SECFailure; 1.935 + } 1.936 + 1.937 + PreliminaryHandshakeDone(fd); 1.938 + 1.939 + uint32_t reasonsForNotFalseStarting = 0; 1.940 + 1.941 + SSLChannelInfo channelInfo; 1.942 + if (SSL_GetChannelInfo(fd, &channelInfo, sizeof(channelInfo)) != SECSuccess) { 1.943 + return SECSuccess; 1.944 + } 1.945 + 1.946 + SSLCipherSuiteInfo cipherInfo; 1.947 + if (SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo, 1.948 + sizeof (cipherInfo)) != SECSuccess) { 1.949 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CanFalseStartCallback [%p] failed - " 1.950 + " KEA %d\n", fd, 1.951 + static_cast<int32_t>(cipherInfo.keaType))); 1.952 + return SECSuccess; 1.953 + } 1.954 + 1.955 + nsSSLIOLayerHelpers& helpers = infoObject->SharedState().IOLayerHelpers(); 1.956 + 1.957 + // Prevent version downgrade attacks from TLS 1.x to SSL 3.0. 1.958 + // TODO(bug 861310): If we negotiate less than our highest-supported version, 1.959 + // then check that a previously-completed handshake negotiated that version; 1.960 + // eventually, require that the highest-supported version of TLS is used. 1.961 + if (channelInfo.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_0) { 1.962 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CanFalseStartCallback [%p] failed - " 1.963 + "SSL Version must be >= TLS1 %x\n", fd, 1.964 + static_cast<int32_t>(channelInfo.protocolVersion))); 1.965 + reasonsForNotFalseStarting |= POSSIBLE_VERSION_DOWNGRADE; 1.966 + } 1.967 + 1.968 + // never do false start without one of these key exchange algorithms 1.969 + if (cipherInfo.keaType != ssl_kea_rsa && 1.970 + cipherInfo.keaType != ssl_kea_dh && 1.971 + cipherInfo.keaType != ssl_kea_ecdh) { 1.972 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CanFalseStartCallback [%p] failed - " 1.973 + "unsupported KEA %d\n", fd, 1.974 + static_cast<int32_t>(cipherInfo.keaType))); 1.975 + reasonsForNotFalseStarting |= KEA_NOT_SUPPORTED; 1.976 + } 1.977 + 1.978 + // XXX: This assumes that all TLS_DH_* and TLS_ECDH_* cipher suites 1.979 + // are disabled. 1.980 + if (cipherInfo.keaType != ssl_kea_ecdh && 1.981 + cipherInfo.keaType != ssl_kea_dh) { 1.982 + if (helpers.mFalseStartRequireForwardSecrecy) { 1.983 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.984 + ("CanFalseStartCallback [%p] failed - KEA used is %d, but " 1.985 + "require-forward-secrecy configured.\n", fd, 1.986 + static_cast<int32_t>(cipherInfo.keaType))); 1.987 + reasonsForNotFalseStarting |= KEA_NOT_FORWARD_SECRET; 1.988 + } else if (cipherInfo.keaType == ssl_kea_rsa) { 1.989 + // Make sure we've seen the same kea from this host in the past, to limit 1.990 + // the potential for downgrade attacks. 1.991 + int16_t expected = infoObject->GetKEAExpected(); 1.992 + if (cipherInfo.keaType != expected) { 1.993 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.994 + ("CanFalseStartCallback [%p] failed - " 1.995 + "KEA used is %d, expected %d\n", fd, 1.996 + static_cast<int32_t>(cipherInfo.keaType), 1.997 + static_cast<int32_t>(expected))); 1.998 + reasonsForNotFalseStarting |= KEA_NOT_SAME_AS_EXPECTED; 1.999 + } 1.1000 + } else { 1.1001 + reasonsForNotFalseStarting |= KEA_NOT_ALLOWED; 1.1002 + } 1.1003 + } 1.1004 + 1.1005 + // Prevent downgrade attacks on the symmetric cipher. We accept downgrades 1.1006 + // from 256-bit keys to 128-bit keys and we treat AES and Camellia as being 1.1007 + // equally secure. We consider every message authentication mechanism that we 1.1008 + // support *for these ciphers* to be equally-secure. We assume that for CBC 1.1009 + // mode, that the server has implemented all the same mitigations for 1.1010 + // published attacks that we have, or that those attacks are not relevant in 1.1011 + // the decision to false start. 1.1012 + if (cipherInfo.symCipher != ssl_calg_aes_gcm && 1.1013 + cipherInfo.symCipher != ssl_calg_aes && 1.1014 + cipherInfo.symCipher != ssl_calg_camellia) { 1.1015 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.1016 + ("CanFalseStartCallback [%p] failed - Symmetric cipher used, %d, " 1.1017 + "is not supported with False Start.\n", fd, 1.1018 + static_cast<int32_t>(cipherInfo.symCipher))); 1.1019 + reasonsForNotFalseStarting |= POSSIBLE_CIPHER_SUITE_DOWNGRADE; 1.1020 + } 1.1021 + 1.1022 + // XXX: An attacker can choose which protocols are advertised in the 1.1023 + // NPN extension. TODO(Bug 861311): We should restrict the ability 1.1024 + // of an attacker leverage this capability by restricting false start 1.1025 + // to the same protocol we previously saw for the server, after the 1.1026 + // first successful connection to the server. 1.1027 + 1.1028 + // Enforce NPN to do false start if policy requires it. Do this as an 1.1029 + // indicator if server compatibility. 1.1030 + if (helpers.mFalseStartRequireNPN) { 1.1031 + nsAutoCString negotiatedNPN; 1.1032 + if (NS_FAILED(infoObject->GetNegotiatedNPN(negotiatedNPN)) || 1.1033 + !negotiatedNPN.Length()) { 1.1034 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CanFalseStartCallback [%p] failed - " 1.1035 + "NPN cannot be verified\n", fd)); 1.1036 + reasonsForNotFalseStarting |= NPN_NOT_NEGOTIATED; 1.1037 + } 1.1038 + } 1.1039 + 1.1040 + Telemetry::Accumulate(Telemetry::SSL_REASONS_FOR_NOT_FALSE_STARTING, 1.1041 + reasonsForNotFalseStarting); 1.1042 + 1.1043 + if (reasonsForNotFalseStarting == 0) { 1.1044 + *canFalseStart = PR_TRUE; 1.1045 + infoObject->SetFalseStarted(); 1.1046 + infoObject->NoteTimeUntilReady(); 1.1047 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CanFalseStartCallback [%p] ok\n", fd)); 1.1048 + } 1.1049 + 1.1050 + return SECSuccess; 1.1051 +} 1.1052 + 1.1053 +static void 1.1054 +AccumulateNonECCKeySize(Telemetry::ID probe, uint32_t bits) 1.1055 +{ 1.1056 + unsigned int value = bits < 512 ? 1 : bits == 512 ? 2 1.1057 + : bits < 768 ? 3 : bits == 768 ? 4 1.1058 + : bits < 1024 ? 5 : bits == 1024 ? 6 1.1059 + : bits < 1280 ? 7 : bits == 1280 ? 8 1.1060 + : bits < 1536 ? 9 : bits == 1536 ? 10 1.1061 + : bits < 2048 ? 11 : bits == 2048 ? 12 1.1062 + : bits < 3072 ? 13 : bits == 3072 ? 14 1.1063 + : bits < 4096 ? 15 : bits == 4096 ? 16 1.1064 + : bits < 8192 ? 17 : bits == 8192 ? 18 1.1065 + : bits < 16384 ? 19 : bits == 16384 ? 20 1.1066 + : 0; 1.1067 + Telemetry::Accumulate(probe, value); 1.1068 +} 1.1069 + 1.1070 +// XXX: This attempts to map a bit count to an ECC named curve identifier. In 1.1071 +// the vast majority of situations, we only have the Suite B curves available. 1.1072 +// In that case, this mapping works fine. If we were to have more curves 1.1073 +// available, the mapping would be ambiguous since there could be multiple 1.1074 +// named curves for a given size (e.g. secp256k1 vs. secp256r1). We punt on 1.1075 +// that for now. See also NSS bug 323674. 1.1076 +static void 1.1077 +AccumulateECCCurve(Telemetry::ID probe, uint32_t bits) 1.1078 +{ 1.1079 + unsigned int value = bits == 256 ? 23 // P-256 1.1080 + : bits == 384 ? 24 // P-384 1.1081 + : bits == 521 ? 25 // P-521 1.1082 + : 0; // Unknown 1.1083 + Telemetry::Accumulate(probe, value); 1.1084 +} 1.1085 + 1.1086 +static void 1.1087 +AccumulateCipherSuite(Telemetry::ID probe, const SSLChannelInfo& channelInfo) 1.1088 +{ 1.1089 + uint32_t value; 1.1090 + switch (channelInfo.cipherSuite) { 1.1091 + // ECDHE key exchange 1.1092 + case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: value = 1; break; 1.1093 + case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: value = 2; break; 1.1094 + case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: value = 3; break; 1.1095 + case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: value = 4; break; 1.1096 + case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: value = 5; break; 1.1097 + case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: value = 6; break; 1.1098 + case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: value = 7; break; 1.1099 + case TLS_ECDHE_RSA_WITH_RC4_128_SHA: value = 8; break; 1.1100 + case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: value = 9; break; 1.1101 + case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: value = 10; break; 1.1102 + // DHE key exchange 1.1103 + case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: value = 21; break; 1.1104 + case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: value = 22; break; 1.1105 + case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: value = 23; break; 1.1106 + case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: value = 24; break; 1.1107 + case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: value = 25; break; 1.1108 + case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: value = 26; break; 1.1109 + case TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: value = 27; break; 1.1110 + case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: value = 28; break; 1.1111 + case TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: value = 29; break; 1.1112 + case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: value = 30; break; 1.1113 + // ECDH key exchange 1.1114 + case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: value = 41; break; 1.1115 + case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: value = 42; break; 1.1116 + case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: value = 43; break; 1.1117 + case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: value = 44; break; 1.1118 + case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: value = 45; break; 1.1119 + case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: value = 46; break; 1.1120 + case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: value = 47; break; 1.1121 + case TLS_ECDH_RSA_WITH_RC4_128_SHA: value = 48; break; 1.1122 + // RSA key exchange 1.1123 + case TLS_RSA_WITH_AES_128_CBC_SHA: value = 61; break; 1.1124 + case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: value = 62; break; 1.1125 + case TLS_RSA_WITH_AES_256_CBC_SHA: value = 63; break; 1.1126 + case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: value = 64; break; 1.1127 + case SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA: value = 65; break; 1.1128 + case TLS_RSA_WITH_3DES_EDE_CBC_SHA: value = 66; break; 1.1129 + case TLS_RSA_WITH_SEED_CBC_SHA: value = 67; break; 1.1130 + case TLS_RSA_WITH_RC4_128_SHA: value = 68; break; 1.1131 + case TLS_RSA_WITH_RC4_128_MD5: value = 69; break; 1.1132 + // unknown 1.1133 + default: 1.1134 + value = 0; 1.1135 + break; 1.1136 + } 1.1137 + MOZ_ASSERT(value != 0); 1.1138 + Telemetry::Accumulate(probe, value); 1.1139 +} 1.1140 + 1.1141 +void HandshakeCallback(PRFileDesc* fd, void* client_data) { 1.1142 + nsNSSShutDownPreventionLock locker; 1.1143 + SECStatus rv; 1.1144 + 1.1145 + nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret; 1.1146 + 1.1147 + // Do the bookkeeping that needs to be done after the 1.1148 + // server's ServerHello...ServerHelloDone have been processed, but that doesn't 1.1149 + // need the handshake to be completed. 1.1150 + PreliminaryHandshakeDone(fd); 1.1151 + 1.1152 + nsSSLIOLayerHelpers& ioLayerHelpers 1.1153 + = infoObject->SharedState().IOLayerHelpers(); 1.1154 + 1.1155 + SSLVersionRange versions(infoObject->GetTLSVersionRange()); 1.1156 + 1.1157 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.1158 + ("[%p] HandshakeCallback: succeeded using TLS version range (0x%04x,0x%04x)\n", 1.1159 + fd, static_cast<unsigned int>(versions.min), 1.1160 + static_cast<unsigned int>(versions.max))); 1.1161 + 1.1162 + // If the handshake completed, then we know the site is TLS tolerant 1.1163 + ioLayerHelpers.rememberTolerantAtVersion(infoObject->GetHostName(), 1.1164 + infoObject->GetPort(), 1.1165 + versions.max); 1.1166 + 1.1167 + PRBool siteSupportsSafeRenego; 1.1168 + rv = SSL_HandshakeNegotiatedExtension(fd, ssl_renegotiation_info_xtn, 1.1169 + &siteSupportsSafeRenego); 1.1170 + MOZ_ASSERT(rv == SECSuccess); 1.1171 + if (rv != SECSuccess) { 1.1172 + siteSupportsSafeRenego = false; 1.1173 + } 1.1174 + 1.1175 + if (siteSupportsSafeRenego || 1.1176 + !ioLayerHelpers.treatUnsafeNegotiationAsBroken()) { 1.1177 + infoObject->SetSecurityState(nsIWebProgressListener::STATE_IS_SECURE | 1.1178 + nsIWebProgressListener::STATE_SECURE_HIGH); 1.1179 + } else { 1.1180 + infoObject->SetSecurityState(nsIWebProgressListener::STATE_IS_BROKEN); 1.1181 + } 1.1182 + 1.1183 + // XXX Bug 883674: We shouldn't be formatting messages here in PSM; instead, 1.1184 + // we should set a flag on the channel that higher (UI) level code can check 1.1185 + // to log the warning. In particular, these warnings should go to the web 1.1186 + // console instead of to the error console. Also, the warning is not 1.1187 + // localized. 1.1188 + if (!siteSupportsSafeRenego && 1.1189 + ioLayerHelpers.getWarnLevelMissingRFC5746() > 0) { 1.1190 + nsXPIDLCString hostName; 1.1191 + infoObject->GetHostName(getter_Copies(hostName)); 1.1192 + 1.1193 + nsAutoString msg; 1.1194 + msg.Append(NS_ConvertASCIItoUTF16(hostName)); 1.1195 + msg.Append(NS_LITERAL_STRING(" : server does not support RFC 5746, see CVE-2009-3555")); 1.1196 + 1.1197 + nsContentUtils::LogSimpleConsoleError(msg, "SSL"); 1.1198 + } 1.1199 + 1.1200 + mozilla::pkix::ScopedCERTCertificate serverCert(SSL_PeerCertificate(fd)); 1.1201 + 1.1202 + /* Set the SSL Status information */ 1.1203 + RefPtr<nsSSLStatus> status(infoObject->SSLStatus()); 1.1204 + if (!status) { 1.1205 + status = new nsSSLStatus(); 1.1206 + infoObject->SetSSLStatus(status); 1.1207 + } 1.1208 + 1.1209 + RememberCertErrorsTable::GetInstance().LookupCertErrorBits(infoObject, 1.1210 + status); 1.1211 + 1.1212 + RefPtr<nsNSSCertificate> nssc(nsNSSCertificate::Create(serverCert.get())); 1.1213 + nsCOMPtr<nsIX509Cert> prevcert; 1.1214 + infoObject->GetPreviousCert(getter_AddRefs(prevcert)); 1.1215 + 1.1216 + bool equals_previous = false; 1.1217 + if (prevcert && nssc) { 1.1218 + nsresult rv = nssc->Equals(prevcert, &equals_previous); 1.1219 + if (NS_FAILED(rv)) { 1.1220 + equals_previous = false; 1.1221 + } 1.1222 + } 1.1223 + 1.1224 + if (equals_previous) { 1.1225 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.1226 + ("HandshakeCallback using PREV cert %p\n", prevcert.get())); 1.1227 + status->mServerCert = prevcert; 1.1228 + } 1.1229 + else { 1.1230 + if (status->mServerCert) { 1.1231 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.1232 + ("HandshakeCallback KEEPING cert %p\n", status->mServerCert.get())); 1.1233 + } 1.1234 + else { 1.1235 + PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, 1.1236 + ("HandshakeCallback using NEW cert %p\n", nssc.get())); 1.1237 + status->mServerCert = nssc; 1.1238 + } 1.1239 + } 1.1240 + 1.1241 + SSLChannelInfo channelInfo; 1.1242 + rv = SSL_GetChannelInfo(fd, &channelInfo, sizeof(channelInfo)); 1.1243 + MOZ_ASSERT(rv == SECSuccess); 1.1244 + if (rv == SECSuccess) { 1.1245 + // Get the protocol version for telemetry 1.1246 + // 0=ssl3, 1=tls1, 2=tls1.1, 3=tls1.2 1.1247 + unsigned int versionEnum = channelInfo.protocolVersion & 0xFF; 1.1248 + Telemetry::Accumulate(Telemetry::SSL_HANDSHAKE_VERSION, versionEnum); 1.1249 + AccumulateCipherSuite( 1.1250 + infoObject->IsFullHandshake() ? Telemetry::SSL_CIPHER_SUITE_FULL 1.1251 + : Telemetry::SSL_CIPHER_SUITE_RESUMED, 1.1252 + channelInfo); 1.1253 + 1.1254 + SSLCipherSuiteInfo cipherInfo; 1.1255 + rv = SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo, 1.1256 + sizeof cipherInfo); 1.1257 + MOZ_ASSERT(rv == SECSuccess); 1.1258 + if (rv == SECSuccess) { 1.1259 + status->mHaveKeyLengthAndCipher = true; 1.1260 + status->mKeyLength = cipherInfo.symKeyBits; 1.1261 + status->mSecretKeyLength = cipherInfo.effectiveKeyBits; 1.1262 + status->mCipherName.Assign(cipherInfo.cipherSuiteName); 1.1263 + 1.1264 + // keyExchange null=0, rsa=1, dh=2, fortezza=3, ecdh=4 1.1265 + Telemetry::Accumulate( 1.1266 + infoObject->IsFullHandshake() 1.1267 + ? Telemetry::SSL_KEY_EXCHANGE_ALGORITHM_FULL 1.1268 + : Telemetry::SSL_KEY_EXCHANGE_ALGORITHM_RESUMED, 1.1269 + cipherInfo.keaType); 1.1270 + infoObject->SetKEAUsed(cipherInfo.keaType); 1.1271 + 1.1272 + if (infoObject->IsFullHandshake()) { 1.1273 + switch (cipherInfo.keaType) { 1.1274 + case ssl_kea_rsa: 1.1275 + AccumulateNonECCKeySize(Telemetry::SSL_KEA_RSA_KEY_SIZE_FULL, 1.1276 + channelInfo.keaKeyBits); 1.1277 + break; 1.1278 + case ssl_kea_dh: 1.1279 + AccumulateNonECCKeySize(Telemetry::SSL_KEA_DHE_KEY_SIZE_FULL, 1.1280 + channelInfo.keaKeyBits); 1.1281 + break; 1.1282 + case ssl_kea_ecdh: 1.1283 + AccumulateECCCurve(Telemetry::SSL_KEA_ECDHE_CURVE_FULL, 1.1284 + channelInfo.keaKeyBits); 1.1285 + break; 1.1286 + default: 1.1287 + MOZ_CRASH("impossible KEA"); 1.1288 + break; 1.1289 + } 1.1290 + 1.1291 + Telemetry::Accumulate(Telemetry::SSL_AUTH_ALGORITHM_FULL, 1.1292 + cipherInfo.authAlgorithm); 1.1293 + 1.1294 + // RSA key exchange doesn't use a signature for auth. 1.1295 + if (cipherInfo.keaType != ssl_kea_rsa) { 1.1296 + switch (cipherInfo.authAlgorithm) { 1.1297 + case ssl_auth_rsa: 1.1298 + AccumulateNonECCKeySize(Telemetry::SSL_AUTH_RSA_KEY_SIZE_FULL, 1.1299 + channelInfo.authKeyBits); 1.1300 + break; 1.1301 + case ssl_auth_dsa: 1.1302 + AccumulateNonECCKeySize(Telemetry::SSL_AUTH_DSA_KEY_SIZE_FULL, 1.1303 + channelInfo.authKeyBits); 1.1304 + break; 1.1305 + case ssl_auth_ecdsa: 1.1306 + AccumulateECCCurve(Telemetry::SSL_AUTH_ECDSA_CURVE_FULL, 1.1307 + channelInfo.authKeyBits); 1.1308 + break; 1.1309 + default: 1.1310 + MOZ_CRASH("impossible auth algorithm"); 1.1311 + break; 1.1312 + } 1.1313 + } 1.1314 + } 1.1315 + 1.1316 + Telemetry::Accumulate( 1.1317 + infoObject->IsFullHandshake() 1.1318 + ? Telemetry::SSL_SYMMETRIC_CIPHER_FULL 1.1319 + : Telemetry::SSL_SYMMETRIC_CIPHER_RESUMED, 1.1320 + cipherInfo.symCipher); 1.1321 + } 1.1322 + } 1.1323 + 1.1324 + infoObject->NoteTimeUntilReady(); 1.1325 + infoObject->SetHandshakeCompleted(); 1.1326 +}