1/*************************************************************************** 2 * _ _ ____ _ 3 * Project ___| | | | _ \| | 4 * / __| | | | |_) | | 5 * | (__| |_| | _ <| |___ 6 * \___|\___/|_| \_\_____| 7 * 8 * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. 9 * 10 * This software is licensed as described in the file COPYING, which 11 * you should have received as part of this distribution. The terms 12 * are also available at http://curl.haxx.se/docs/copyright.html. 13 * 14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell 15 * copies of the Software, and permit persons to whom the Software is 16 * furnished to do so, under the terms of the COPYING file. 17 * 18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY 19 * KIND, either express or implied. 20 * 21 ***************************************************************************/ 22 23/* 24 * Source file for all NSS-specific code for the TLS/SSL layer. No code 25 * but sslgen.c should ever call or use these functions. 26 */ 27 28#include "setup.h" 29 30#include <string.h> 31#include <stdlib.h> 32#include <ctype.h> 33#ifdef HAVE_SYS_SOCKET_H 34#include <sys/socket.h> 35#endif 36 37#include "urldata.h" 38#include "sendf.h" 39#include "formdata.h" /* for the boundary function */ 40#include "url.h" /* for the ssl config check function */ 41#include "connect.h" 42#include "strequal.h" 43#include "select.h" 44#include "sslgen.h" 45#include "llist.h" 46 47#define _MPRINTF_REPLACE /* use the internal *printf() functions */ 48#include <curl/mprintf.h> 49 50#ifdef USE_NSS 51 52#include "nssg.h" 53#include <nspr.h> 54#include <nss.h> 55#include <ssl.h> 56#include <sslerr.h> 57#include <secerr.h> 58#include <secmod.h> 59#include <sslproto.h> 60#include <prtypes.h> 61#include <pk11pub.h> 62#include <prio.h> 63#include <secitem.h> 64#include <secport.h> 65#include <certdb.h> 66#include <base64.h> 67#include <cert.h> 68 69#include "curl_memory.h" 70#include "rawstr.h" 71 72/* The last #include file should be: */ 73#include "memdebug.h" 74 75#define SSL_DIR "/etc/pki/nssdb" 76 77/* enough to fit the string "PEM Token #[0|1]" */ 78#define SLOTSIZE 13 79 80PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd); 81 82PRLock * nss_initlock = NULL; 83PRLock * nss_crllock = NULL; 84 85volatile int initialized = 0; 86 87typedef struct { 88 const char *name; 89 int num; 90 PRInt32 version; /* protocol version valid for this cipher */ 91} cipher_s; 92 93#define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \ 94 CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \ 95 ptr->type = (_type); \ 96 ptr->pValue = (_val); \ 97 ptr->ulValueLen = (_len); \ 98} while(0) 99 100#define CERT_NewTempCertificate __CERT_NewTempCertificate 101 102enum sslversion { SSL2 = 1, SSL3 = 2, TLS = 4 }; 103 104#define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0]) 105static const cipher_s cipherlist[] = { 106 /* SSL2 cipher suites */ 107 {"rc4", SSL_EN_RC4_128_WITH_MD5, SSL2}, 108 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5, SSL2}, 109 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL2}, 110 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5, SSL2}, 111 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL2}, 112 {"des", SSL_EN_DES_64_CBC_WITH_MD5, SSL2}, 113 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL2}, 114 /* SSL3/TLS cipher suites */ 115 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5, SSL3 | TLS}, 116 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA, SSL3 | TLS}, 117 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS}, 118 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA, SSL3 | TLS}, 119 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL3 | TLS}, 120 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL3 | TLS}, 121 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5, SSL3 | TLS}, 122 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA, SSL3 | TLS}, 123 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS}, 124 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL3 | TLS}, 125 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, SSL3 | TLS}, 126 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, SSL3 | TLS}, 127 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA, SSL3 | TLS}, 128 /* TLS 1.0: Exportable 56-bit Cipher Suites. */ 129 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL3 | TLS}, 130 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL3 | TLS}, 131 /* AES ciphers. */ 132 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA, SSL3 | TLS}, 133 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA, SSL3 | TLS}, 134#ifdef NSS_ENABLE_ECC 135 /* ECC ciphers. */ 136 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA, TLS}, 137 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS}, 138 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS}, 139 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS}, 140 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS}, 141 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS}, 142 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS}, 143 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS}, 144 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS}, 145 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS}, 146 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA, TLS}, 147 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS}, 148 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS}, 149 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS}, 150 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS}, 151 {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA, TLS}, 152 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS}, 153 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS}, 154 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS}, 155 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS}, 156 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA, TLS}, 157 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA, TLS}, 158 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, TLS}, 159 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS}, 160 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA, TLS}, 161#endif 162}; 163 164/* following ciphers are new in NSS 3.4 and not enabled by default, therefore 165 they are enabled explicitly */ 166static const int enable_ciphers_by_default[] = { 167 TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 168 TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 169 TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 170 TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 171 TLS_RSA_WITH_AES_128_CBC_SHA, 172 TLS_RSA_WITH_AES_256_CBC_SHA, 173 SSL_NULL_WITH_NULL_NULL 174}; 175 176#ifdef HAVE_PK11_CREATEGENERICOBJECT 177static const char* pem_library = "libnsspem.so"; 178#endif 179SECMODModule* mod = NULL; 180 181static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model, 182 char *cipher_list) 183{ 184 unsigned int i; 185 PRBool cipher_state[NUM_OF_CIPHERS]; 186 PRBool found; 187 char *cipher; 188 SECStatus rv; 189 190 /* First disable all ciphers. This uses a different max value in case 191 * NSS adds more ciphers later we don't want them available by 192 * accident 193 */ 194 for(i=0; i<SSL_NumImplementedCiphers; i++) { 195 SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED); 196 } 197 198 /* Set every entry in our list to false */ 199 for(i=0; i<NUM_OF_CIPHERS; i++) { 200 cipher_state[i] = PR_FALSE; 201 } 202 203 cipher = cipher_list; 204 205 while(cipher_list && (cipher_list[0])) { 206 while((*cipher) && (ISSPACE(*cipher))) 207 ++cipher; 208 209 if((cipher_list = strchr(cipher, ','))) { 210 *cipher_list++ = '\0'; 211 } 212 213 found = PR_FALSE; 214 215 for(i=0; i<NUM_OF_CIPHERS; i++) { 216 if(Curl_raw_equal(cipher, cipherlist[i].name)) { 217 cipher_state[i] = PR_TRUE; 218 found = PR_TRUE; 219 break; 220 } 221 } 222 223 if(found == PR_FALSE) { 224 failf(data, "Unknown cipher in list: %s", cipher); 225 return SECFailure; 226 } 227 228 if(cipher_list) { 229 cipher = cipher_list; 230 } 231 } 232 233 /* Finally actually enable the selected ciphers */ 234 for(i=0; i<NUM_OF_CIPHERS; i++) { 235 rv = SSL_CipherPrefSet(model, cipherlist[i].num, cipher_state[i]); 236 if(rv != SECSuccess) { 237 failf(data, "Unknown cipher in cipher list"); 238 return SECFailure; 239 } 240 } 241 242 return SECSuccess; 243} 244 245/* 246 * Get the number of ciphers that are enabled. We use this to determine 247 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers. 248 */ 249static int num_enabled_ciphers(void) 250{ 251 PRInt32 policy = 0; 252 int count = 0; 253 unsigned int i; 254 255 for(i=0; i<NUM_OF_CIPHERS; i++) { 256 SSL_CipherPolicyGet(cipherlist[i].num, &policy); 257 if(policy) 258 count++; 259 } 260 return count; 261} 262 263/* 264 * Determine whether the nickname passed in is a filename that needs to 265 * be loaded as a PEM or a regular NSS nickname. 266 * 267 * returns 1 for a file 268 * returns 0 for not a file (NSS nickname) 269 */ 270static int is_file(const char *filename) 271{ 272 struct_stat st; 273 274 if(filename == NULL) 275 return 0; 276 277 if(stat(filename, &st) == 0) 278 if(S_ISREG(st.st_mode)) 279 return 1; 280 281 return 0; 282} 283 284/* Return on heap allocated filename/nickname of a certificate. The returned 285 * string should be later deallocated using free(). *is_nickname is set to 286 * TRUE if the given string is treated as nickname; FALSE if the given string 287 * is treated as file name. 288 */ 289static char *fmt_nickname(struct SessionHandle *data, enum dupstring cert_kind, 290 bool *is_nickname) 291{ 292 const char *str = data->set.str[cert_kind]; 293 const char *n; 294 *is_nickname = TRUE; 295 296 if(!is_file(str)) 297 /* no such file exists, use the string as nickname */ 298 return strdup(str); 299 300 /* search the last slash; we require at least one slash in a file name */ 301 n = strrchr(str, '/'); 302 if(!n) { 303 infof(data, "warning: certificate file name \"%s\" handled as nickname; " 304 "please use \"./%s\" to force file name\n", str, str); 305 return strdup(str); 306 } 307 308 /* we'll use the PEM reader to read the certificate from file */ 309 *is_nickname = FALSE; 310 311 n++; /* skip last slash */ 312 return aprintf("PEM Token #%d:%s", 1, n); 313} 314 315#ifdef HAVE_PK11_CREATEGENERICOBJECT 316/* Call PK11_CreateGenericObject() with the given obj_class and filename. If 317 * the call succeeds, append the object handle to the list of objects so that 318 * the object can be destroyed in Curl_nss_close(). */ 319static CURLcode nss_create_object(struct ssl_connect_data *ssl, 320 CK_OBJECT_CLASS obj_class, 321 const char *filename, bool cacert) 322{ 323 PK11SlotInfo *slot; 324 PK11GenericObject *obj; 325 CK_BBOOL cktrue = CK_TRUE; 326 CK_BBOOL ckfalse = CK_FALSE; 327 CK_ATTRIBUTE attrs[/* max count of attributes */ 4]; 328 int attr_cnt = 0; 329 330 const int slot_id = (cacert) ? 0 : 1; 331 char *slot_name = aprintf("PEM Token #%d", slot_id); 332 if(!slot_name) 333 return CURLE_OUT_OF_MEMORY; 334 335 slot = PK11_FindSlotByName(slot_name); 336 free(slot_name); 337 if(!slot) 338 return CURLE_SSL_CERTPROBLEM; 339 340 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class)); 341 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL)); 342 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename, 343 strlen(filename) + 1); 344 345 if(CKO_CERTIFICATE == obj_class) { 346 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse); 347 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval)); 348 } 349 350 obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE); 351 PK11_FreeSlot(slot); 352 if(!obj) 353 return CURLE_SSL_CERTPROBLEM; 354 355 if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) { 356 PK11_DestroyGenericObject(obj); 357 return CURLE_OUT_OF_MEMORY; 358 } 359 360 return CURLE_OK; 361} 362 363/* Destroy the NSS object whose handle is given by ptr. This function is 364 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy 365 * NSS objects in Curl_nss_close() */ 366static void nss_destroy_object(void *user, void *ptr) 367{ 368 PK11GenericObject *obj = (PK11GenericObject *)ptr; 369 (void) user; 370 PK11_DestroyGenericObject(obj); 371} 372#endif 373 374static int nss_load_cert(struct ssl_connect_data *ssl, 375 const char *filename, PRBool cacert) 376{ 377#ifdef HAVE_PK11_CREATEGENERICOBJECT 378 /* All CA and trust objects go into slot 0. Other slots are used 379 * for storing certificates. 380 */ 381 const int slot_id = (cacert) ? 0 : 1; 382#endif 383 CERTCertificate *cert; 384 char *nickname = NULL; 385 char *n = NULL; 386 387 /* If there is no slash in the filename it is assumed to be a regular 388 * NSS nickname. 389 */ 390 if(is_file(filename)) { 391 n = strrchr(filename, '/'); 392 if(n) 393 n++; 394 if(!mod) 395 return 1; 396 } 397 else { 398 /* A nickname from the NSS internal database */ 399 if(cacert) 400 return 0; /* You can't specify an NSS CA nickname this way */ 401 nickname = strdup(filename); 402 if(!nickname) 403 return 0; 404 goto done; 405 } 406 407#ifdef HAVE_PK11_CREATEGENERICOBJECT 408 nickname = aprintf("PEM Token #%d:%s", slot_id, n); 409 if(!nickname) 410 return 0; 411 412 if(CURLE_OK != nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert)) { 413 free(nickname); 414 return 0; 415 } 416 417#else 418 /* We don't have PK11_CreateGenericObject but a file-based cert was passed 419 * in. We need to fail. 420 */ 421 return 0; 422#endif 423 424 done: 425 /* Double-check that the certificate or nickname requested exists in 426 * either the token or the NSS certificate database. 427 */ 428 if(!cacert) { 429 cert = PK11_FindCertFromNickname((char *)nickname, NULL); 430 431 /* An invalid nickname was passed in */ 432 if(cert == NULL) { 433 free(nickname); 434 PR_SetError(SEC_ERROR_UNKNOWN_CERT, 0); 435 return 0; 436 } 437 438 CERT_DestroyCertificate(cert); 439 } 440 441 free(nickname); 442 443 return 1; 444} 445 446/* add given CRL to cache if it is not already there */ 447static SECStatus nss_cache_crl(SECItem *crlDER) 448{ 449 CERTCertDBHandle *db = CERT_GetDefaultCertDB(); 450 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0); 451 if(crl) { 452 /* CRL already cached */ 453 SEC_DestroyCrl(crl); 454 SECITEM_FreeItem(crlDER, PR_FALSE); 455 return SECSuccess; 456 } 457 458 /* acquire lock before call of CERT_CacheCRL() */ 459 PR_Lock(nss_crllock); 460 if(SECSuccess != CERT_CacheCRL(db, crlDER)) { 461 /* unable to cache CRL */ 462 PR_Unlock(nss_crllock); 463 SECITEM_FreeItem(crlDER, PR_FALSE); 464 return SECFailure; 465 } 466 467 /* we need to clear session cache, so that the CRL could take effect */ 468 SSL_ClearSessionCache(); 469 PR_Unlock(nss_crllock); 470 return SECSuccess; 471} 472 473static SECStatus nss_load_crl(const char* crlfilename) 474{ 475 PRFileDesc *infile; 476 PRFileInfo info; 477 SECItem filedata = { 0, NULL, 0 }; 478 SECItem crlDER = { 0, NULL, 0 }; 479 char *body; 480 481 infile = PR_Open(crlfilename, PR_RDONLY, 0); 482 if(!infile) 483 return SECFailure; 484 485 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info)) 486 goto fail; 487 488 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1)) 489 goto fail; 490 491 if(info.size != PR_Read(infile, filedata.data, info.size)) 492 goto fail; 493 494 /* place a trailing zero right after the visible data */ 495 body = (char*)filedata.data; 496 body[--filedata.len] = '\0'; 497 498 body = strstr(body, "-----BEGIN"); 499 if(body) { 500 /* assume ASCII */ 501 char *trailer; 502 char *begin = PORT_Strchr(body, '\n'); 503 if(!begin) 504 begin = PORT_Strchr(body, '\r'); 505 if(!begin) 506 goto fail; 507 508 trailer = strstr(++begin, "-----END"); 509 if(!trailer) 510 goto fail; 511 512 /* retrieve DER from ASCII */ 513 *trailer = '\0'; 514 if(ATOB_ConvertAsciiToItem(&crlDER, begin)) 515 goto fail; 516 517 SECITEM_FreeItem(&filedata, PR_FALSE); 518 } 519 else 520 /* assume DER */ 521 crlDER = filedata; 522 523 PR_Close(infile); 524 return nss_cache_crl(&crlDER); 525 526fail: 527 PR_Close(infile); 528 SECITEM_FreeItem(&filedata, PR_FALSE); 529 return SECFailure; 530} 531 532static int nss_load_key(struct connectdata *conn, int sockindex, 533 char *key_file) 534{ 535#ifdef HAVE_PK11_CREATEGENERICOBJECT 536 PK11SlotInfo *slot; 537 SECStatus status; 538 struct ssl_connect_data *ssl = conn->ssl; 539 (void)sockindex; /* unused */ 540 541 if(CURLE_OK != nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE)) { 542 PR_SetError(SEC_ERROR_BAD_KEY, 0); 543 return 0; 544 } 545 546 slot = PK11_FindSlotByName("PEM Token #1"); 547 if(!slot) 548 return 0; 549 550 /* This will force the token to be seen as re-inserted */ 551 SECMOD_WaitForAnyTokenEvent(mod, 0, 0); 552 PK11_IsPresent(slot); 553 554 status = PK11_Authenticate(slot, PR_TRUE, 555 conn->data->set.str[STRING_KEY_PASSWD]); 556 PK11_FreeSlot(slot); 557 return (SECSuccess == status) ? 1 : 0; 558#else 559 /* If we don't have PK11_CreateGenericObject then we can't load a file-based 560 * key. 561 */ 562 (void)conn; /* unused */ 563 (void)key_file; /* unused */ 564 (void)sockindex; /* unused */ 565 return 0; 566#endif 567} 568 569static int display_error(struct connectdata *conn, PRInt32 err, 570 const char *filename) 571{ 572 switch(err) { 573 case SEC_ERROR_BAD_PASSWORD: 574 failf(conn->data, "Unable to load client key: Incorrect password"); 575 return 1; 576 case SEC_ERROR_UNKNOWN_CERT: 577 failf(conn->data, "Unable to load certificate %s", filename); 578 return 1; 579 default: 580 break; 581 } 582 return 0; /* The caller will print a generic error */ 583} 584 585static int cert_stuff(struct connectdata *conn, 586 int sockindex, char *cert_file, char *key_file) 587{ 588 struct SessionHandle *data = conn->data; 589 int rv = 0; 590 591 if(cert_file) { 592 rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE); 593 if(!rv) { 594 if(!display_error(conn, PR_GetError(), cert_file)) 595 failf(data, "Unable to load client cert %d.", PR_GetError()); 596 return 0; 597 } 598 } 599 if(key_file || (is_file(cert_file))) { 600 if(key_file) 601 rv = nss_load_key(conn, sockindex, key_file); 602 else 603 /* In case the cert file also has the key */ 604 rv = nss_load_key(conn, sockindex, cert_file); 605 if(!rv) { 606 if(!display_error(conn, PR_GetError(), key_file)) 607 failf(data, "Unable to load client key %d.", PR_GetError()); 608 609 return 0; 610 } 611 } 612 return 1; 613} 614 615static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg) 616{ 617 (void)slot; /* unused */ 618 if(retry || NULL == arg) 619 return NULL; 620 else 621 return (char *)PORT_Strdup((char *)arg); 622} 623 624/* bypass the default SSL_AuthCertificate() hook in case we do not want to 625 * verify peer */ 626static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig, 627 PRBool isServer) 628{ 629 struct connectdata *conn = (struct connectdata *)arg; 630 if(!conn->data->set.ssl.verifypeer) { 631 infof(conn->data, "skipping SSL peer certificate verification\n"); 632 return SECSuccess; 633 } 634 635 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer); 636} 637 638static SECStatus BadCertHandler(void *arg, PRFileDesc *sock) 639{ 640 SECStatus result = SECFailure; 641 struct connectdata *conn = (struct connectdata *)arg; 642 PRErrorCode err = PR_GetError(); 643 CERTCertificate *cert = NULL; 644 char *subject, *subject_cn, *issuer; 645 646 conn->data->set.ssl.certverifyresult=err; 647 cert = SSL_PeerCertificate(sock); 648 subject = CERT_NameToAscii(&cert->subject); 649 subject_cn = CERT_GetCommonName(&cert->subject); 650 issuer = CERT_NameToAscii(&cert->issuer); 651 CERT_DestroyCertificate(cert); 652 653 switch(err) { 654 case SEC_ERROR_CA_CERT_INVALID: 655 infof(conn->data, "Issuer certificate is invalid: '%s'\n", issuer); 656 break; 657 case SEC_ERROR_UNTRUSTED_ISSUER: 658 infof(conn->data, "Certificate is signed by an untrusted issuer: '%s'\n", 659 issuer); 660 break; 661 case SSL_ERROR_BAD_CERT_DOMAIN: 662 if(conn->data->set.ssl.verifyhost) { 663 failf(conn->data, "SSL: certificate subject name '%s' does not match " 664 "target host name '%s'", subject_cn, conn->host.dispname); 665 } 666 else { 667 result = SECSuccess; 668 infof(conn->data, "warning: SSL: certificate subject name '%s' does not " 669 "match target host name '%s'\n", subject_cn, conn->host.dispname); 670 } 671 break; 672 case SEC_ERROR_EXPIRED_CERTIFICATE: 673 infof(conn->data, "Remote Certificate has expired.\n"); 674 break; 675 case SEC_ERROR_UNKNOWN_ISSUER: 676 infof(conn->data, "Peer's certificate issuer is not recognized: '%s'\n", 677 issuer); 678 break; 679 default: 680 infof(conn->data, "Bad certificate received. Subject = '%s', " 681 "Issuer = '%s'\n", subject, issuer); 682 break; 683 } 684 if(result == SECSuccess) 685 infof(conn->data, "SSL certificate verify ok.\n"); 686 PR_Free(subject); 687 PR_Free(subject_cn); 688 PR_Free(issuer); 689 690 return result; 691} 692 693/** 694 * Inform the application that the handshake is complete. 695 */ 696static SECStatus HandshakeCallback(PRFileDesc *sock, void *arg) 697{ 698 (void)sock; 699 (void)arg; 700 return SECSuccess; 701} 702 703static void display_cert_info(struct SessionHandle *data, 704 CERTCertificate *cert) 705{ 706 char *subject, *issuer, *common_name; 707 PRExplodedTime printableTime; 708 char timeString[256]; 709 PRTime notBefore, notAfter; 710 711 subject = CERT_NameToAscii(&cert->subject); 712 issuer = CERT_NameToAscii(&cert->issuer); 713 common_name = CERT_GetCommonName(&cert->subject); 714 infof(data, "\tsubject: %s\n", subject); 715 716 CERT_GetCertTimes(cert, ¬Before, ¬After); 717 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime); 718 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime); 719 infof(data, "\tstart date: %s\n", timeString); 720 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime); 721 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime); 722 infof(data, "\texpire date: %s\n", timeString); 723 infof(data, "\tcommon name: %s\n", common_name); 724 infof(data, "\tissuer: %s\n", issuer); 725 726 PR_Free(subject); 727 PR_Free(issuer); 728 PR_Free(common_name); 729} 730 731static void display_conn_info(struct connectdata *conn, PRFileDesc *sock) 732{ 733 SSLChannelInfo channel; 734 SSLCipherSuiteInfo suite; 735 CERTCertificate *cert; 736 737 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) == 738 SECSuccess && channel.length == sizeof channel && 739 channel.cipherSuite) { 740 if(SSL_GetCipherSuiteInfo(channel.cipherSuite, 741 &suite, sizeof suite) == SECSuccess) { 742 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName); 743 } 744 } 745 746 infof(conn->data, "Server certificate:\n"); 747 748 cert = SSL_PeerCertificate(sock); 749 display_cert_info(conn->data, cert); 750 CERT_DestroyCertificate(cert); 751 752 return; 753} 754 755/** 756 * 757 * Check that the Peer certificate's issuer certificate matches the one found 758 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the 759 * issuer check, so we provide comments that mimic the OpenSSL 760 * X509_check_issued function (in x509v3/v3_purp.c) 761 */ 762static SECStatus check_issuer_cert(PRFileDesc *sock, 763 char *issuer_nickname) 764{ 765 CERTCertificate *cert,*cert_issuer,*issuer; 766 SECStatus res=SECSuccess; 767 void *proto_win = NULL; 768 769 /* 770 PRArenaPool *tmpArena = NULL; 771 CERTAuthKeyID *authorityKeyID = NULL; 772 SECITEM *caname = NULL; 773 */ 774 775 cert = SSL_PeerCertificate(sock); 776 cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner); 777 778 proto_win = SSL_RevealPinArg(sock); 779 issuer = NULL; 780 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win); 781 782 if((!cert_issuer) || (!issuer)) 783 res = SECFailure; 784 else if(SECITEM_CompareItem(&cert_issuer->derCert, 785 &issuer->derCert)!=SECEqual) 786 res = SECFailure; 787 788 CERT_DestroyCertificate(cert); 789 CERT_DestroyCertificate(issuer); 790 CERT_DestroyCertificate(cert_issuer); 791 return res; 792} 793 794/** 795 * 796 * Callback to pick the SSL client certificate. 797 */ 798static SECStatus SelectClientCert(void *arg, PRFileDesc *sock, 799 struct CERTDistNamesStr *caNames, 800 struct CERTCertificateStr **pRetCert, 801 struct SECKEYPrivateKeyStr **pRetKey) 802{ 803 static const char pem_nickname[] = "PEM Token #1"; 804 const char *pem_slotname = pem_nickname; 805 806 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg; 807 struct SessionHandle *data = connssl->data; 808 const char *nickname = connssl->client_nickname; 809 810 if(mod && nickname && 811 0 == strncmp(nickname, pem_nickname, /* length of "PEM Token" */ 9)) { 812 813 /* use the cert/key provided by PEM reader */ 814 PK11SlotInfo *slot; 815 void *proto_win = SSL_RevealPinArg(sock); 816 *pRetKey = NULL; 817 818 *pRetCert = PK11_FindCertFromNickname(nickname, proto_win); 819 if(NULL == *pRetCert) { 820 failf(data, "NSS: client certificate not found: %s", nickname); 821 return SECFailure; 822 } 823 824 slot = PK11_FindSlotByName(pem_slotname); 825 if(NULL == slot) { 826 failf(data, "NSS: PK11 slot not found: %s", pem_slotname); 827 return SECFailure; 828 } 829 830 *pRetKey = PK11_FindPrivateKeyFromCert(slot, *pRetCert, NULL); 831 PK11_FreeSlot(slot); 832 if(NULL == *pRetKey) { 833 failf(data, "NSS: private key not found for certificate: %s", nickname); 834 return SECFailure; 835 } 836 837 infof(data, "NSS: client certificate: %s\n", nickname); 838 display_cert_info(data, *pRetCert); 839 return SECSuccess; 840 } 841 842 /* use the default NSS hook */ 843 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames, 844 pRetCert, pRetKey) 845 || NULL == *pRetCert) { 846 847 if(NULL == nickname) 848 failf(data, "NSS: client certificate not found (nickname not " 849 "specified)"); 850 else 851 failf(data, "NSS: client certificate not found: %s", nickname); 852 853 return SECFailure; 854 } 855 856 /* get certificate nickname if any */ 857 nickname = (*pRetCert)->nickname; 858 if(NULL == nickname) 859 nickname = "[unknown]"; 860 861 if(NULL == *pRetKey) { 862 failf(data, "NSS: private key not found for certificate: %s", nickname); 863 return SECFailure; 864 } 865 866 infof(data, "NSS: using client certificate: %s\n", nickname); 867 display_cert_info(data, *pRetCert); 868 return SECSuccess; 869} 870 871/* This function is supposed to decide, which error codes should be used 872 * to conclude server is TLS intolerant. 873 * 874 * taken from xulrunner - nsNSSIOLayer.cpp 875 */ 876static PRBool 877isTLSIntoleranceError(PRInt32 err) 878{ 879 switch (err) { 880 case SSL_ERROR_BAD_MAC_ALERT: 881 case SSL_ERROR_BAD_MAC_READ: 882 case SSL_ERROR_HANDSHAKE_FAILURE_ALERT: 883 case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT: 884 case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE: 885 case SSL_ERROR_ILLEGAL_PARAMETER_ALERT: 886 case SSL_ERROR_NO_CYPHER_OVERLAP: 887 case SSL_ERROR_BAD_SERVER: 888 case SSL_ERROR_BAD_BLOCK_PADDING: 889 case SSL_ERROR_UNSUPPORTED_VERSION: 890 case SSL_ERROR_PROTOCOL_VERSION_ALERT: 891 case SSL_ERROR_RX_MALFORMED_FINISHED: 892 case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE: 893 case SSL_ERROR_DECODE_ERROR_ALERT: 894 case SSL_ERROR_RX_UNKNOWN_ALERT: 895 return PR_TRUE; 896 default: 897 return PR_FALSE; 898 } 899} 900 901static CURLcode init_nss(struct SessionHandle *data) 902{ 903 char *cert_dir; 904 struct_stat st; 905 if(initialized) 906 return CURLE_OK; 907 908 /* First we check if $SSL_DIR points to a valid dir */ 909 cert_dir = getenv("SSL_DIR"); 910 if(cert_dir) { 911 if((stat(cert_dir, &st) != 0) || 912 (!S_ISDIR(st.st_mode))) { 913 cert_dir = NULL; 914 } 915 } 916 917 /* Now we check if the default location is a valid dir */ 918 if(!cert_dir) { 919 if((stat(SSL_DIR, &st) == 0) && 920 (S_ISDIR(st.st_mode))) { 921 cert_dir = (char *)SSL_DIR; 922 } 923 } 924 925 if(!NSS_IsInitialized()) { 926 SECStatus rv; 927 initialized = 1; 928 infof(data, "Initializing NSS with certpath: %s\n", 929 cert_dir ? cert_dir : "none"); 930 if(!cert_dir) { 931 rv = NSS_NoDB_Init(NULL); 932 } 933 else { 934 char *certpath = 935 PR_smprintf("%s%s", NSS_VersionCheck("3.12.0") ? "sql:" : "", 936 cert_dir); 937 rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY); 938 PR_smprintf_free(certpath); 939 } 940 if(rv != SECSuccess) { 941 infof(data, "Unable to initialize NSS database\n"); 942 initialized = 0; 943 return CURLE_SSL_CACERT_BADFILE; 944 } 945 } 946 947 if(num_enabled_ciphers() == 0) 948 NSS_SetDomesticPolicy(); 949 950 return CURLE_OK; 951} 952 953/** 954 * Global SSL init 955 * 956 * @retval 0 error initializing SSL 957 * @retval 1 SSL initialized successfully 958 */ 959int Curl_nss_init(void) 960{ 961 /* curl_global_init() is not thread-safe so this test is ok */ 962 if(nss_initlock == NULL) { 963 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256); 964 nss_initlock = PR_NewLock(); 965 nss_crllock = PR_NewLock(); 966 } 967 968 /* We will actually initialize NSS later */ 969 970 return 1; 971} 972 973CURLcode Curl_nss_force_init(struct SessionHandle *data) 974{ 975 CURLcode rv; 976 if(!nss_initlock) { 977 failf(data, 978 "unable to initialize NSS, curl_global_init() should have been " 979 "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL"); 980 return CURLE_FAILED_INIT; 981 } 982 983 PR_Lock(nss_initlock); 984 rv = init_nss(data); 985 PR_Unlock(nss_initlock); 986 return rv; 987} 988 989/* Global cleanup */ 990void Curl_nss_cleanup(void) 991{ 992 /* This function isn't required to be threadsafe and this is only done 993 * as a safety feature. 994 */ 995 PR_Lock(nss_initlock); 996 if(initialized) { 997 /* Free references to client certificates held in the SSL session cache. 998 * Omitting this hampers destruction of the security module owning 999 * the certificates. */ 1000 SSL_ClearSessionCache(); 1001 1002 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) { 1003 SECMOD_DestroyModule(mod); 1004 mod = NULL; 1005 } 1006 NSS_Shutdown(); 1007 } 1008 PR_Unlock(nss_initlock); 1009 1010 PR_DestroyLock(nss_initlock); 1011 PR_DestroyLock(nss_crllock); 1012 nss_initlock = NULL; 1013 1014 initialized = 0; 1015} 1016 1017/* 1018 * This function uses SSL_peek to determine connection status. 1019 * 1020 * Return codes: 1021 * 1 means the connection is still in place 1022 * 0 means the connection has been closed 1023 * -1 means the connection status is unknown 1024 */ 1025int 1026Curl_nss_check_cxn(struct connectdata *conn) 1027{ 1028 int rc; 1029 char buf; 1030 1031 rc = 1032 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK, 1033 PR_SecondsToInterval(1)); 1034 if(rc > 0) 1035 return 1; /* connection still in place */ 1036 1037 if(rc == 0) 1038 return 0; /* connection has been closed */ 1039 1040 return -1; /* connection status unknown */ 1041} 1042 1043/* 1044 * This function is called when an SSL connection is closed. 1045 */ 1046void Curl_nss_close(struct connectdata *conn, int sockindex) 1047{ 1048 struct ssl_connect_data *connssl = &conn->ssl[sockindex]; 1049 1050 if(connssl->handle) { 1051 /* NSS closes the socket we previously handed to it, so we must mark it 1052 as closed to avoid double close */ 1053 fake_sclose(conn->sock[sockindex]); 1054 conn->sock[sockindex] = CURL_SOCKET_BAD; 1055 if(connssl->client_nickname != NULL) { 1056 free(connssl->client_nickname); 1057 connssl->client_nickname = NULL; 1058 1059 /* force NSS to ask again for a client cert when connecting 1060 * next time to the same server */ 1061 SSL_InvalidateSession(connssl->handle); 1062 } 1063#ifdef HAVE_PK11_CREATEGENERICOBJECT 1064 /* destroy all NSS objects in order to avoid failure of NSS shutdown */ 1065 Curl_llist_destroy(connssl->obj_list, NULL); 1066 connssl->obj_list = NULL; 1067#endif 1068 PR_Close(connssl->handle); 1069 connssl->handle = NULL; 1070 } 1071} 1072 1073/* 1074 * This function is called when the 'data' struct is going away. Close 1075 * down everything and free all resources! 1076 */ 1077int Curl_nss_close_all(struct SessionHandle *data) 1078{ 1079 (void)data; 1080 return 0; 1081} 1082 1083/* handle client certificate related errors if any; return false otherwise */ 1084static bool handle_cc_error(PRInt32 err, struct SessionHandle *data) 1085{ 1086 switch(err) { 1087 case SSL_ERROR_BAD_CERT_ALERT: 1088 failf(data, "SSL error: SSL_ERROR_BAD_CERT_ALERT"); 1089 return true; 1090 1091 case SSL_ERROR_REVOKED_CERT_ALERT: 1092 failf(data, "SSL error: SSL_ERROR_REVOKED_CERT_ALERT"); 1093 return true; 1094 1095 case SSL_ERROR_EXPIRED_CERT_ALERT: 1096 failf(data, "SSL error: SSL_ERROR_EXPIRED_CERT_ALERT"); 1097 return true; 1098 1099 default: 1100 return false; 1101 } 1102} 1103 1104static Curl_recv nss_recv; 1105static Curl_send nss_send; 1106 1107static CURLcode nss_load_ca_certificates(struct connectdata *conn, 1108 int sockindex) 1109{ 1110 struct SessionHandle *data = conn->data; 1111 const char *cafile = data->set.ssl.CAfile; 1112 const char *capath = data->set.ssl.CApath; 1113 1114 if(cafile && !nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE)) 1115 return CURLE_SSL_CACERT_BADFILE; 1116 1117 if(capath) { 1118 struct_stat st; 1119 if(stat(capath, &st) == -1) 1120 return CURLE_SSL_CACERT_BADFILE; 1121 1122 if(S_ISDIR(st.st_mode)) { 1123 PRDirEntry *entry; 1124 PRDir *dir = PR_OpenDir(capath); 1125 if(!dir) 1126 return CURLE_SSL_CACERT_BADFILE; 1127 1128 while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) { 1129 char *fullpath = aprintf("%s/%s", capath, entry->name); 1130 if(!fullpath) { 1131 PR_CloseDir(dir); 1132 return CURLE_OUT_OF_MEMORY; 1133 } 1134 1135 if(!nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE)) 1136 /* This is purposefully tolerant of errors so non-PEM files can 1137 * be in the same directory */ 1138 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath); 1139 1140 free(fullpath); 1141 } 1142 1143 PR_CloseDir(dir); 1144 } 1145 else 1146 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath); 1147 } 1148 1149 infof(data, " CAfile: %s\n CApath: %s\n", 1150 cafile ? cafile : "none", 1151 capath ? capath : "none"); 1152 1153 return CURLE_OK; 1154} 1155 1156CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex) 1157{ 1158 PRInt32 err; 1159 PRFileDesc *model = NULL; 1160 PRBool ssl2 = PR_FALSE; 1161 PRBool ssl3 = PR_FALSE; 1162 PRBool tlsv1 = PR_FALSE; 1163 PRBool ssl_no_cache; 1164 struct SessionHandle *data = conn->data; 1165 curl_socket_t sockfd = conn->sock[sockindex]; 1166 struct ssl_connect_data *connssl = &conn->ssl[sockindex]; 1167 CURLcode curlerr; 1168 const int *cipher_to_enable; 1169 PRSocketOptionData sock_opt; 1170 long time_left; 1171 PRUint32 timeout; 1172 1173 if(connssl->state == ssl_connection_complete) 1174 return CURLE_OK; 1175 1176 connssl->data = data; 1177 1178#ifdef HAVE_PK11_CREATEGENERICOBJECT 1179 /* list of all NSS objects we need to destroy in Curl_nss_close() */ 1180 connssl->obj_list = Curl_llist_alloc(nss_destroy_object); 1181 if(!connssl->obj_list) 1182 return CURLE_OUT_OF_MEMORY; 1183#endif 1184 1185 /* FIXME. NSS doesn't support multiple databases open at the same time. */ 1186 PR_Lock(nss_initlock); 1187 curlerr = init_nss(conn->data); 1188 if(CURLE_OK != curlerr) { 1189 PR_Unlock(nss_initlock); 1190 goto error; 1191 } 1192 1193 curlerr = CURLE_SSL_CONNECT_ERROR; 1194 1195#ifdef HAVE_PK11_CREATEGENERICOBJECT 1196 if(!mod) { 1197 char *configstring = aprintf("library=%s name=PEM", pem_library); 1198 if(!configstring) { 1199 PR_Unlock(nss_initlock); 1200 goto error; 1201 } 1202 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE); 1203 free(configstring); 1204 1205 if(!mod || !mod->loaded) { 1206 if(mod) { 1207 SECMOD_DestroyModule(mod); 1208 mod = NULL; 1209 } 1210 infof(data, "WARNING: failed to load NSS PEM library %s. Using " 1211 "OpenSSL PEM certificates will not work.\n", pem_library); 1212 } 1213 } 1214#endif 1215 1216 PK11_SetPasswordFunc(nss_get_password); 1217 PR_Unlock(nss_initlock); 1218 1219 model = PR_NewTCPSocket(); 1220 if(!model) 1221 goto error; 1222 model = SSL_ImportFD(NULL, model); 1223 1224 /* make the socket nonblocking */ 1225 sock_opt.option = PR_SockOpt_Nonblocking; 1226 sock_opt.value.non_blocking = PR_TRUE; 1227 if(PR_SetSocketOption(model, &sock_opt) != PR_SUCCESS) 1228 goto error; 1229 1230 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess) 1231 goto error; 1232 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess) 1233 goto error; 1234 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess) 1235 goto error; 1236 1237 /* do not use SSL cache if we are not going to verify peer */ 1238 ssl_no_cache = (data->set.ssl.verifypeer) ? PR_FALSE : PR_TRUE; 1239 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess) 1240 goto error; 1241 1242 switch (data->set.ssl.version) { 1243 default: 1244 case CURL_SSLVERSION_DEFAULT: 1245 ssl3 = PR_TRUE; 1246 if(data->state.ssl_connect_retry) 1247 infof(data, "TLS disabled due to previous handshake failure\n"); 1248 else 1249 tlsv1 = PR_TRUE; 1250 break; 1251 case CURL_SSLVERSION_TLSv1: 1252 tlsv1 = PR_TRUE; 1253 break; 1254 case CURL_SSLVERSION_SSLv2: 1255 ssl2 = PR_TRUE; 1256 break; 1257 case CURL_SSLVERSION_SSLv3: 1258 ssl3 = PR_TRUE; 1259 break; 1260 } 1261 1262 if(SSL_OptionSet(model, SSL_ENABLE_SSL2, ssl2) != SECSuccess) 1263 goto error; 1264 if(SSL_OptionSet(model, SSL_ENABLE_SSL3, ssl3) != SECSuccess) 1265 goto error; 1266 if(SSL_OptionSet(model, SSL_ENABLE_TLS, tlsv1) != SECSuccess) 1267 goto error; 1268 1269 if(SSL_OptionSet(model, SSL_V2_COMPATIBLE_HELLO, ssl2) != SECSuccess) 1270 goto error; 1271 1272 /* reset the flag to avoid an infinite loop */ 1273 data->state.ssl_connect_retry = FALSE; 1274 1275 /* enable all ciphers from enable_ciphers_by_default */ 1276 cipher_to_enable = enable_ciphers_by_default; 1277 while(SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) { 1278 if(SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) { 1279 curlerr = CURLE_SSL_CIPHER; 1280 goto error; 1281 } 1282 cipher_to_enable++; 1283 } 1284 1285 if(data->set.ssl.cipher_list) { 1286 if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) { 1287 curlerr = CURLE_SSL_CIPHER; 1288 goto error; 1289 } 1290 } 1291 1292 if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost) 1293 infof(data, "warning: ignoring value of ssl.verifyhost\n"); 1294 else if(data->set.ssl.verifyhost == 1) 1295 infof(data, "warning: ignoring unsupported value (1) of ssl.verifyhost\n"); 1296 1297 /* bypass the default SSL_AuthCertificate() hook in case we do not want to 1298 * verify peer */ 1299 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess) 1300 goto error; 1301 1302 data->set.ssl.certverifyresult=0; /* not checked yet */ 1303 if(SSL_BadCertHook(model, (SSLBadCertHandler) BadCertHandler, conn) 1304 != SECSuccess) { 1305 goto error; 1306 } 1307 if(SSL_HandshakeCallback(model, (SSLHandshakeCallback) HandshakeCallback, 1308 NULL) != SECSuccess) 1309 goto error; 1310 1311 if(data->set.ssl.verifypeer) { 1312 const CURLcode rv = nss_load_ca_certificates(conn, sockindex); 1313 if(CURLE_OK != rv) { 1314 curlerr = rv; 1315 goto error; 1316 } 1317 } 1318 1319 if(data->set.ssl.CRLfile) { 1320 if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) { 1321 curlerr = CURLE_SSL_CRL_BADFILE; 1322 goto error; 1323 } 1324 infof(data, 1325 " CRLfile: %s\n", 1326 data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none"); 1327 } 1328 1329 if(data->set.str[STRING_CERT]) { 1330 bool is_nickname; 1331 char *nickname = fmt_nickname(data, STRING_CERT, &is_nickname); 1332 if(!nickname) 1333 return CURLE_OUT_OF_MEMORY; 1334 1335 if(!is_nickname && !cert_stuff(conn, sockindex, data->set.str[STRING_CERT], 1336 data->set.str[STRING_KEY])) { 1337 /* failf() is already done in cert_stuff() */ 1338 free(nickname); 1339 return CURLE_SSL_CERTPROBLEM; 1340 } 1341 1342 /* store the nickname for SelectClientCert() called during handshake */ 1343 connssl->client_nickname = nickname; 1344 } 1345 else 1346 connssl->client_nickname = NULL; 1347 1348 if(SSL_GetClientAuthDataHook(model, SelectClientCert, 1349 (void *)connssl) != SECSuccess) { 1350 curlerr = CURLE_SSL_CERTPROBLEM; 1351 goto error; 1352 } 1353 1354 /* Import our model socket onto the existing file descriptor */ 1355 connssl->handle = PR_ImportTCPSocket(sockfd); 1356 connssl->handle = SSL_ImportFD(model, connssl->handle); 1357 if(!connssl->handle) 1358 goto error; 1359 1360 PR_Close(model); /* We don't need this any more */ 1361 model = NULL; 1362 1363 /* This is the password associated with the cert that we're using */ 1364 if(data->set.str[STRING_KEY_PASSWD]) { 1365 SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]); 1366 } 1367 1368 /* Force handshake on next I/O */ 1369 SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE); 1370 1371 SSL_SetURL(connssl->handle, conn->host.name); 1372 1373 /* check timeout situation */ 1374 time_left = Curl_timeleft(data, NULL, TRUE); 1375 if(time_left < 0L) { 1376 failf(data, "timed out before SSL handshake"); 1377 goto error; 1378 } 1379 timeout = PR_MillisecondsToInterval((PRUint32) time_left); 1380 1381 /* Force the handshake now */ 1382 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) { 1383 if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN) 1384 curlerr = CURLE_PEER_FAILED_VERIFICATION; 1385 else if(conn->data->set.ssl.certverifyresult!=0) 1386 curlerr = CURLE_SSL_CACERT; 1387 goto error; 1388 } 1389 1390 connssl->state = ssl_connection_complete; 1391 conn->recv[sockindex] = nss_recv; 1392 conn->send[sockindex] = nss_send; 1393 1394 display_conn_info(conn, connssl->handle); 1395 1396 if(data->set.str[STRING_SSL_ISSUERCERT]) { 1397 SECStatus ret = SECFailure; 1398 bool is_nickname; 1399 char *nickname = fmt_nickname(data, STRING_SSL_ISSUERCERT, &is_nickname); 1400 if(!nickname) 1401 return CURLE_OUT_OF_MEMORY; 1402 1403 if(is_nickname) 1404 /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */ 1405 ret = check_issuer_cert(connssl->handle, nickname); 1406 1407 free(nickname); 1408 1409 if(SECFailure == ret) { 1410 infof(data,"SSL certificate issuer check failed\n"); 1411 curlerr = CURLE_SSL_ISSUER_ERROR; 1412 goto error; 1413 } 1414 else { 1415 infof(data, "SSL certificate issuer check ok\n"); 1416 } 1417 } 1418 1419 return CURLE_OK; 1420 1421 error: 1422 /* reset the flag to avoid an infinite loop */ 1423 data->state.ssl_connect_retry = FALSE; 1424 1425 err = PR_GetError(); 1426 if(handle_cc_error(err, data)) 1427 curlerr = CURLE_SSL_CERTPROBLEM; 1428 else 1429 infof(data, "NSS error %d\n", err); 1430 1431 if(model) 1432 PR_Close(model); 1433 1434#ifdef HAVE_PK11_CREATEGENERICOBJECT 1435 /* cleanup on connection failure */ 1436 Curl_llist_destroy(connssl->obj_list, NULL); 1437 connssl->obj_list = NULL; 1438#endif 1439 1440 if(ssl3 && tlsv1 && isTLSIntoleranceError(err)) { 1441 /* schedule reconnect through Curl_retry_request() */ 1442 data->state.ssl_connect_retry = TRUE; 1443 infof(data, "Error in TLS handshake, trying SSLv3...\n"); 1444 return CURLE_OK; 1445 } 1446 1447 return curlerr; 1448} 1449 1450static ssize_t nss_send(struct connectdata *conn, /* connection data */ 1451 int sockindex, /* socketindex */ 1452 const void *mem, /* send this data */ 1453 size_t len, /* amount to write */ 1454 CURLcode *curlcode) 1455{ 1456 int rc; 1457 1458 rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0, -1); 1459 1460 if(rc < 0) { 1461 PRInt32 err = PR_GetError(); 1462 if(err == PR_WOULD_BLOCK_ERROR) 1463 *curlcode = CURLE_AGAIN; 1464 else if(handle_cc_error(err, conn->data)) 1465 *curlcode = CURLE_SSL_CERTPROBLEM; 1466 else { 1467 failf(conn->data, "SSL write: error %d", err); 1468 *curlcode = CURLE_SEND_ERROR; 1469 } 1470 return -1; 1471 } 1472 return rc; /* number of bytes */ 1473} 1474 1475static ssize_t nss_recv(struct connectdata * conn, /* connection data */ 1476 int num, /* socketindex */ 1477 char *buf, /* store read data here */ 1478 size_t buffersize, /* max amount to read */ 1479 CURLcode *curlcode) 1480{ 1481 ssize_t nread; 1482 1483 nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0, -1); 1484 if(nread < 0) { 1485 /* failed SSL read */ 1486 PRInt32 err = PR_GetError(); 1487 1488 if(err == PR_WOULD_BLOCK_ERROR) 1489 *curlcode = CURLE_AGAIN; 1490 else if(handle_cc_error(err, conn->data)) 1491 *curlcode = CURLE_SSL_CERTPROBLEM; 1492 else { 1493 failf(conn->data, "SSL read: errno %d", err); 1494 *curlcode = CURLE_RECV_ERROR; 1495 } 1496 return -1; 1497 } 1498 return nread; 1499} 1500 1501size_t Curl_nss_version(char *buffer, size_t size) 1502{ 1503 return snprintf(buffer, size, "NSS/%s", NSS_VERSION); 1504} 1505 1506int Curl_nss_seed(struct SessionHandle *data) 1507{ 1508 /* TODO: implement? */ 1509 (void) data; 1510 return 0; 1511} 1512 1513#endif /* USE_NSS */ 1514