nss.c 65 KB

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