nss.c 72 KB

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