nss.c 57 KB

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