nss.c 74 KB

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