2
0

nss.c 75 KB

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