nss.c 71 KB

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