nss.c 75 KB

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