1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/nss_ssl_util.h"
15 #include "base/bind.h"
17 #include "base/lazy_instance.h"
18 #include "base/logging.h"
19 #include "base/memory/singleton.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/values.h"
22 #include "build/build_config.h"
23 #include "crypto/nss_util.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/nss_memio.h"
26 #include "net/log/net_log.h"
29 #include "base/win/windows_version.h"
36 // CiphersRemove takes a zero-terminated array of cipher suite ids in
37 // |to_remove| and sets every instance of them in |ciphers| to zero. It returns
38 // true if it found and removed every element of |to_remove|. It assumes that
39 // there are no duplicates in |ciphers| nor in |to_remove|.
40 bool CiphersRemove(const uint16
* to_remove
, uint16
* ciphers
, size_t num
) {
44 if (to_remove
[i
] == 0)
47 for (size_t j
= 0; j
< num
; j
++) {
48 if (to_remove
[i
] == ciphers
[j
]) {
59 // CiphersCompact takes an array of cipher suite ids in |ciphers|, where some
60 // entries are zero, and moves the entries so that all the non-zero elements
61 // are compacted at the end of the array.
62 void CiphersCompact(uint16
* ciphers
, size_t num
) {
65 for (size_t i
= num
- 1; i
< num
; i
--) {
68 ciphers
[j
--] = ciphers
[i
];
72 // CiphersCopy copies the zero-terminated array |in| to |out|. It returns the
73 // number of cipher suite ids copied.
74 size_t CiphersCopy(const uint16
* in
, uint16
* out
) {
75 for (size_t i
= 0; ; i
++) {
82 scoped_ptr
<base::Value
> NetLogSSLErrorCallback(
85 NetLogCaptureMode
/* capture_mode */) {
86 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
87 dict
->SetInteger("net_error", net_error
);
89 dict
->SetInteger("ssl_lib_error", ssl_lib_error
);
93 class NSSSSLInitSingleton
{
95 NSSSSLInitSingleton() : model_fd_(NULL
) {
96 crypto::EnsureNSSInit();
98 NSS_SetDomesticPolicy();
100 const PRUint16
* const ssl_ciphers
= SSL_GetImplementedCiphers();
101 const PRUint16 num_ciphers
= SSL_GetNumImplementedCiphers();
103 // Disable ECDSA cipher suites on platforms that do not support ECDSA
104 // signed certificates, as servers may use the presence of such
105 // ciphersuites as a hint to send an ECDSA certificate.
106 bool disableECDSA
= false;
108 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
112 // Explicitly enable exactly those ciphers with keys of at least 80 bits.
113 for (int i
= 0; i
< num_ciphers
; i
++) {
114 SSLCipherSuiteInfo info
;
115 if (SSL_GetCipherSuiteInfo(ssl_ciphers
[i
], &info
,
116 sizeof(info
)) == SECSuccess
) {
117 bool enabled
= info
.effectiveKeyBits
>= 80;
118 if (info
.authAlgorithm
== ssl_auth_ecdsa
&& disableECDSA
)
121 // Trim the list of cipher suites in order to keep the size of the
122 // ClientHello down. DSS, ECDH, CAMELLIA, SEED, ECC+3DES, and
123 // HMAC-SHA256 cipher suites are disabled.
124 if (info
.symCipher
== ssl_calg_camellia
||
125 info
.symCipher
== ssl_calg_seed
||
126 (info
.symCipher
== ssl_calg_3des
&& info
.keaType
!= ssl_kea_rsa
) ||
127 info
.authAlgorithm
== ssl_auth_dsa
||
128 info
.macAlgorithm
== ssl_hmac_sha256
||
130 strcmp(info
.keaTypeName
, "ECDH") == 0) {
134 SSL_CipherPrefSetDefault(ssl_ciphers
[i
], enabled
);
139 SSL_OptionSetDefault(SSL_SECURITY
, PR_TRUE
);
141 // Calculate the order of ciphers that we'll use for NSS sockets. (Note
142 // that, even if a cipher is specified in the ordering, it must still be
143 // enabled in order to be included in a ClientHello.)
145 // Our top preference cipher suites are either forward-secret AES-GCM or
146 // forward-secret ChaCha20-Poly1305. If the local machine has AES-NI then
147 // we prefer AES-GCM, otherwise ChaCha20. The remainder of the cipher suite
148 // preference is inheriented from NSS. */
149 static const uint16 chacha_ciphers
[] = {
150 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
,
151 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
,
154 static const uint16 aes_gcm_ciphers
[] = {
155 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
,
156 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
,
157 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
,
160 scoped_ptr
<uint16
[]> ciphers(new uint16
[num_ciphers
]);
161 memcpy(ciphers
.get(), ssl_ciphers
, sizeof(uint16
)*num_ciphers
);
163 if (CiphersRemove(chacha_ciphers
, ciphers
.get(), num_ciphers
) &&
164 CiphersRemove(aes_gcm_ciphers
, ciphers
.get(), num_ciphers
)) {
165 CiphersCompact(ciphers
.get(), num_ciphers
);
167 const uint16
* preference_ciphers
= chacha_ciphers
;
168 const uint16
* other_ciphers
= aes_gcm_ciphers
;
171 if (cpu
.has_aesni() && cpu
.has_avx()) {
172 preference_ciphers
= aes_gcm_ciphers
;
173 other_ciphers
= chacha_ciphers
;
175 unsigned i
= CiphersCopy(preference_ciphers
, ciphers
.get());
176 CiphersCopy(other_ciphers
, &ciphers
[i
]);
178 if ((model_fd_
= memio_CreateIOLayer(1, 1)) == NULL
||
179 SSL_ImportFD(NULL
, model_fd_
) == NULL
||
181 SSL_CipherOrderSet(model_fd_
, ciphers
.get(), num_ciphers
)) {
190 // All other SSL options are set per-session by SSLClientSocket and
194 PRFileDesc
* GetModelSocket() {
198 ~NSSSSLInitSingleton() {
199 // Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
200 SSL_ClearSessionCache();
206 PRFileDesc
* model_fd_
;
209 base::LazyInstance
<NSSSSLInitSingleton
>::Leaky g_nss_ssl_init_singleton
=
210 LAZY_INSTANCE_INITIALIZER
;
212 } // anonymous namespace
214 // Initialize the NSS SSL library if it isn't already initialized. This must
215 // be called before any other NSS SSL functions. This function is
216 // thread-safe, and the NSS SSL library will only ever be initialized once.
217 // The NSS SSL library will be properly shut down on program exit.
218 void EnsureNSSSSLInit() {
219 // Initializing SSL causes us to do blocking IO.
220 // Temporarily allow it until we fix
221 // http://code.google.com/p/chromium/issues/detail?id=59847
222 base::ThreadRestrictions::ScopedAllowIO allow_io
;
224 g_nss_ssl_init_singleton
.Get();
227 PRFileDesc
* GetNSSModelSocket() {
228 return g_nss_ssl_init_singleton
.Get().GetModelSocket();
231 // Map a Chromium net error code to an NSS error code.
232 // See _MD_unix_map_default_error in the NSS source
233 // tree for inspiration.
234 PRErrorCode
MapErrorToNSS(int result
) {
240 return PR_WOULD_BLOCK_ERROR
;
241 case ERR_ACCESS_DENIED
:
242 case ERR_NETWORK_ACCESS_DENIED
:
243 // For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
244 return PR_NO_ACCESS_RIGHTS_ERROR
;
245 case ERR_NOT_IMPLEMENTED
:
246 return PR_NOT_IMPLEMENTED_ERROR
;
247 case ERR_SOCKET_NOT_CONNECTED
:
248 return PR_NOT_CONNECTED_ERROR
;
249 case ERR_INTERNET_DISCONNECTED
: // Equivalent to ENETDOWN.
250 return PR_NETWORK_UNREACHABLE_ERROR
; // Best approximation.
251 case ERR_CONNECTION_TIMED_OUT
:
253 return PR_IO_TIMEOUT_ERROR
;
254 case ERR_CONNECTION_RESET
:
255 return PR_CONNECT_RESET_ERROR
;
256 case ERR_CONNECTION_ABORTED
:
257 return PR_CONNECT_ABORTED_ERROR
;
258 case ERR_CONNECTION_REFUSED
:
259 return PR_CONNECT_REFUSED_ERROR
;
260 case ERR_ADDRESS_UNREACHABLE
:
261 return PR_HOST_UNREACHABLE_ERROR
; // Also PR_NETWORK_UNREACHABLE_ERROR.
262 case ERR_ADDRESS_INVALID
:
263 return PR_ADDRESS_NOT_AVAILABLE_ERROR
;
264 case ERR_NAME_NOT_RESOLVED
:
265 return PR_DIRECTORY_LOOKUP_ERROR
;
267 LOG(WARNING
) << "MapErrorToNSS " << result
268 << " mapped to PR_UNKNOWN_ERROR";
269 return PR_UNKNOWN_ERROR
;
273 // The default error mapping function.
274 // Maps an NSS error code to a network error code.
275 int MapNSSError(PRErrorCode err
) {
276 // TODO(port): fill this out as we learn what's important
278 case PR_WOULD_BLOCK_ERROR
:
279 return ERR_IO_PENDING
;
280 case PR_ADDRESS_NOT_SUPPORTED_ERROR
: // For connect.
281 case PR_NO_ACCESS_RIGHTS_ERROR
:
282 return ERR_ACCESS_DENIED
;
283 case PR_IO_TIMEOUT_ERROR
:
284 return ERR_TIMED_OUT
;
285 case PR_CONNECT_RESET_ERROR
:
286 return ERR_CONNECTION_RESET
;
287 case PR_CONNECT_ABORTED_ERROR
:
288 return ERR_CONNECTION_ABORTED
;
289 case PR_CONNECT_REFUSED_ERROR
:
290 return ERR_CONNECTION_REFUSED
;
291 case PR_NOT_CONNECTED_ERROR
:
292 return ERR_SOCKET_NOT_CONNECTED
;
293 case PR_HOST_UNREACHABLE_ERROR
:
294 case PR_NETWORK_UNREACHABLE_ERROR
:
295 return ERR_ADDRESS_UNREACHABLE
;
296 case PR_ADDRESS_NOT_AVAILABLE_ERROR
:
297 return ERR_ADDRESS_INVALID
;
298 case PR_INVALID_ARGUMENT_ERROR
:
299 return ERR_INVALID_ARGUMENT
;
300 case PR_END_OF_FILE_ERROR
:
301 return ERR_CONNECTION_CLOSED
;
302 case PR_NOT_IMPLEMENTED_ERROR
:
303 return ERR_NOT_IMPLEMENTED
;
305 case SEC_ERROR_LIBRARY_FAILURE
:
306 return ERR_UNEXPECTED
;
307 case SEC_ERROR_INVALID_ARGS
:
308 return ERR_INVALID_ARGUMENT
;
309 case SEC_ERROR_NO_MEMORY
:
310 return ERR_OUT_OF_MEMORY
;
311 case SEC_ERROR_NO_KEY
:
312 return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
;
313 case SEC_ERROR_INVALID_KEY
:
314 case SSL_ERROR_SIGN_HASHES_FAILURE
:
315 LOG(ERROR
) << "ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED: NSS error " << err
316 << ", OS error " << PR_GetOSError();
317 return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
;
318 // A handshake (initial or renegotiation) may fail because some signature
319 // (for example, the signature in the ServerKeyExchange message for an
320 // ephemeral Diffie-Hellman cipher suite) is invalid.
321 case SEC_ERROR_BAD_SIGNATURE
:
322 return ERR_SSL_PROTOCOL_ERROR
;
324 case SSL_ERROR_SSL_DISABLED
:
325 return ERR_NO_SSL_VERSIONS_ENABLED
;
326 case SSL_ERROR_NO_CYPHER_OVERLAP
:
327 case SSL_ERROR_PROTOCOL_VERSION_ALERT
:
328 case SSL_ERROR_UNSUPPORTED_VERSION
:
329 return ERR_SSL_VERSION_OR_CIPHER_MISMATCH
;
330 case SSL_ERROR_HANDSHAKE_FAILURE_ALERT
:
331 case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT
:
332 case SSL_ERROR_ILLEGAL_PARAMETER_ALERT
:
333 return ERR_SSL_PROTOCOL_ERROR
;
334 case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT
:
335 return ERR_SSL_DECOMPRESSION_FAILURE_ALERT
;
336 case SSL_ERROR_BAD_MAC_ALERT
:
337 return ERR_SSL_BAD_RECORD_MAC_ALERT
;
338 case SSL_ERROR_DECRYPT_ERROR_ALERT
:
339 return ERR_SSL_DECRYPT_ERROR_ALERT
;
340 case SSL_ERROR_UNRECOGNIZED_NAME_ALERT
:
341 return ERR_SSL_UNRECOGNIZED_NAME_ALERT
;
342 case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY
:
343 return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY
;
344 case SSL_ERROR_HANDSHAKE_NOT_COMPLETED
:
345 return ERR_SSL_HANDSHAKE_NOT_COMPLETED
;
346 case SEC_ERROR_BAD_KEY
:
347 case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
:
348 // TODO(wtc): the following errors may also occur in contexts unrelated
349 // to the peer's public key. We should add new error codes for them, or
350 // map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
351 // General unsupported/unknown key algorithm error.
352 case SEC_ERROR_UNSUPPORTED_KEYALG
:
353 // General DER decoding errors.
354 case SEC_ERROR_BAD_DER
:
355 case SEC_ERROR_EXTRA_INPUT
:
356 return ERR_SSL_BAD_PEER_PUBLIC_KEY
;
357 // During renegotiation, the server presented a different certificate than
359 case SSL_ERROR_WRONG_CERTIFICATE
:
360 return ERR_SSL_SERVER_CERT_CHANGED
;
361 case SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT
:
362 return ERR_SSL_INAPPROPRIATE_FALLBACK
;
365 const char* err_name
= PR_ErrorToName(err
);
366 if (err_name
== NULL
)
368 if (IS_SSL_ERROR(err
)) {
369 LOG(WARNING
) << "Unknown SSL error " << err
<< " (" << err_name
<< ")"
370 << " mapped to net::ERR_SSL_PROTOCOL_ERROR";
371 return ERR_SSL_PROTOCOL_ERROR
;
373 LOG(WARNING
) << "Unknown error " << err
<< " (" << err_name
<< ")"
374 << " mapped to net::ERR_FAILED";
380 // Returns parameters to attach to the NetLog when we receive an error in
381 // response to a call to an NSS function. Used instead of
382 // NetLogSSLErrorCallback with events of type TYPE_SSL_NSS_ERROR.
383 scoped_ptr
<base::Value
> NetLogSSLFailedNSSFunctionCallback(
384 const char* function
,
387 NetLogCaptureMode
/* capture_mode */) {
388 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
389 dict
->SetString("function", function
);
390 if (param
[0] != '\0')
391 dict
->SetString("param", param
);
392 dict
->SetInteger("ssl_lib_error", ssl_lib_error
);
396 void LogFailedNSSFunction(const BoundNetLog
& net_log
,
397 const char* function
,
402 NetLog::TYPE_SSL_NSS_ERROR
,
403 base::Bind(&NetLogSSLFailedNSSFunctionCallback
,
404 function
, param
, PR_GetError()));
407 NetLog::ParametersCallback
CreateNetLogSSLErrorCallback(int net_error
,
409 return base::Bind(&NetLogSSLErrorCallback
, net_error
, ssl_lib_error
);