2
0

nss.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.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. /* FIXME. NSS doesn't support multiple databases open at the same time. */
  1556. PR_Lock(nss_initlock);
  1557. result = nss_init(conn->data);
  1558. if(result) {
  1559. PR_Unlock(nss_initlock);
  1560. goto error;
  1561. }
  1562. PK11_SetPasswordFunc(nss_get_password);
  1563. result = nss_load_module(&pem_module, pem_library, "PEM");
  1564. PR_Unlock(nss_initlock);
  1565. if(result == CURLE_FAILED_INIT)
  1566. infof(data, "WARNING: failed to load NSS PEM library %s. Using "
  1567. "OpenSSL PEM certificates will not work.\n", pem_library);
  1568. else if(result)
  1569. goto error;
  1570. result = CURLE_SSL_CONNECT_ERROR;
  1571. model = PR_NewTCPSocket();
  1572. if(!model)
  1573. goto error;
  1574. model = SSL_ImportFD(NULL, model);
  1575. if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
  1576. goto error;
  1577. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
  1578. goto error;
  1579. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
  1580. goto error;
  1581. /* do not use SSL cache if disabled or we are not going to verify peer */
  1582. ssl_no_cache = (SSL_SET_OPTION(primary.sessionid)
  1583. && SSL_CONN_CONFIG(verifypeer)) ? PR_FALSE : PR_TRUE;
  1584. if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
  1585. goto error;
  1586. /* enable/disable the requested SSL version(s) */
  1587. if(nss_init_sslver(&sslver, data, conn) != CURLE_OK)
  1588. goto error;
  1589. if(SSL_VersionRangeGetSupported(ssl_variant_stream,
  1590. &sslver_supported) != SECSuccess)
  1591. goto error;
  1592. if(sslver_supported.max < sslver.max && sslver_supported.max >= sslver.min) {
  1593. char *sslver_req_str, *sslver_supp_str;
  1594. sslver_req_str = nss_sslver_to_name(sslver.max);
  1595. sslver_supp_str = nss_sslver_to_name(sslver_supported.max);
  1596. if(sslver_req_str && sslver_supp_str)
  1597. infof(data, "Falling back from %s to max supported SSL version (%s)\n",
  1598. sslver_req_str, sslver_supp_str);
  1599. free(sslver_req_str);
  1600. free(sslver_supp_str);
  1601. sslver.max = sslver_supported.max;
  1602. }
  1603. if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
  1604. goto error;
  1605. ssl_cbc_random_iv = !SSL_SET_OPTION(enable_beast);
  1606. #ifdef SSL_CBC_RANDOM_IV
  1607. /* unless the user explicitly asks to allow the protocol vulnerability, we
  1608. use the work-around */
  1609. if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
  1610. infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
  1611. ssl_cbc_random_iv);
  1612. #else
  1613. if(ssl_cbc_random_iv)
  1614. infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
  1615. #endif
  1616. if(SSL_CONN_CONFIG(cipher_list)) {
  1617. if(set_ciphers(data, model, SSL_CONN_CONFIG(cipher_list)) != SECSuccess) {
  1618. result = CURLE_SSL_CIPHER;
  1619. goto error;
  1620. }
  1621. }
  1622. if(!SSL_CONN_CONFIG(verifypeer) && SSL_CONN_CONFIG(verifyhost))
  1623. infof(data, "warning: ignoring value of ssl.verifyhost\n");
  1624. /* bypass the default SSL_AuthCertificate() hook in case we do not want to
  1625. * verify peer */
  1626. if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
  1627. goto error;
  1628. /* not checked yet */
  1629. if(SSL_IS_PROXY())
  1630. data->set.proxy_ssl.certverifyresult = 0;
  1631. else
  1632. data->set.ssl.certverifyresult = 0;
  1633. if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
  1634. goto error;
  1635. if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
  1636. goto error;
  1637. {
  1638. const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
  1639. if((rv == CURLE_SSL_CACERT_BADFILE) && !SSL_CONN_CONFIG(verifypeer))
  1640. /* not a fatal error because we are not going to verify the peer */
  1641. infof(data, "warning: CA certificates failed to load\n");
  1642. else if(rv) {
  1643. result = rv;
  1644. goto error;
  1645. }
  1646. }
  1647. if(SSL_SET_OPTION(CRLfile)) {
  1648. const CURLcode rv = nss_load_crl(SSL_SET_OPTION(CRLfile));
  1649. if(rv) {
  1650. result = rv;
  1651. goto error;
  1652. }
  1653. infof(data, " CRLfile: %s\n", SSL_SET_OPTION(CRLfile));
  1654. }
  1655. if(SSL_SET_OPTION(cert)) {
  1656. char *nickname = dup_nickname(data, SSL_SET_OPTION(cert));
  1657. if(nickname) {
  1658. /* we are not going to use libnsspem.so to read the client cert */
  1659. BACKEND->obj_clicert = NULL;
  1660. }
  1661. else {
  1662. CURLcode rv = cert_stuff(conn, sockindex, SSL_SET_OPTION(cert),
  1663. SSL_SET_OPTION(key));
  1664. if(rv) {
  1665. /* failf() is already done in cert_stuff() */
  1666. result = rv;
  1667. goto error;
  1668. }
  1669. }
  1670. /* store the nickname for SelectClientCert() called during handshake */
  1671. BACKEND->client_nickname = nickname;
  1672. }
  1673. else
  1674. BACKEND->client_nickname = NULL;
  1675. if(SSL_GetClientAuthDataHook(model, SelectClientCert,
  1676. (void *)connssl) != SECSuccess) {
  1677. result = CURLE_SSL_CERTPROBLEM;
  1678. goto error;
  1679. }
  1680. if(conn->proxy_ssl[sockindex].use) {
  1681. DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
  1682. DEBUGASSERT(conn->proxy_ssl[sockindex].backend->handle != NULL);
  1683. nspr_io = conn->proxy_ssl[sockindex].backend->handle;
  1684. second_layer = TRUE;
  1685. }
  1686. else {
  1687. /* wrap OS file descriptor by NSPR's file descriptor abstraction */
  1688. nspr_io = PR_ImportTCPSocket(sockfd);
  1689. if(!nspr_io)
  1690. goto error;
  1691. }
  1692. /* create our own NSPR I/O layer */
  1693. nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
  1694. if(!nspr_io_stub) {
  1695. if(!second_layer)
  1696. PR_Close(nspr_io);
  1697. goto error;
  1698. }
  1699. /* make the per-connection data accessible from NSPR I/O callbacks */
  1700. nspr_io_stub->secret = (void *)connssl;
  1701. /* push our new layer to the NSPR I/O stack */
  1702. if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
  1703. if(!second_layer)
  1704. PR_Close(nspr_io);
  1705. PR_Close(nspr_io_stub);
  1706. goto error;
  1707. }
  1708. /* import our model socket onto the current I/O stack */
  1709. BACKEND->handle = SSL_ImportFD(model, nspr_io);
  1710. if(!BACKEND->handle) {
  1711. if(!second_layer)
  1712. PR_Close(nspr_io);
  1713. goto error;
  1714. }
  1715. PR_Close(model); /* We don't need this any more */
  1716. model = NULL;
  1717. /* This is the password associated with the cert that we're using */
  1718. if(SSL_SET_OPTION(key_passwd)) {
  1719. SSL_SetPKCS11PinArg(BACKEND->handle, SSL_SET_OPTION(key_passwd));
  1720. }
  1721. #ifdef SSL_ENABLE_OCSP_STAPLING
  1722. if(SSL_CONN_CONFIG(verifystatus)) {
  1723. if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
  1724. != SECSuccess)
  1725. goto error;
  1726. }
  1727. #endif
  1728. #ifdef SSL_ENABLE_NPN
  1729. if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
  1730. ? PR_TRUE : PR_FALSE) != SECSuccess)
  1731. goto error;
  1732. #endif
  1733. #ifdef SSL_ENABLE_ALPN
  1734. if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
  1735. ? PR_TRUE : PR_FALSE) != SECSuccess)
  1736. goto error;
  1737. #endif
  1738. #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
  1739. if(data->set.ssl.falsestart) {
  1740. if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
  1741. != SECSuccess)
  1742. goto error;
  1743. if(SSL_SetCanFalseStartCallback(BACKEND->handle, CanFalseStartCallback,
  1744. conn) != SECSuccess)
  1745. goto error;
  1746. }
  1747. #endif
  1748. #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
  1749. if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
  1750. int cur = 0;
  1751. unsigned char protocols[128];
  1752. #ifdef USE_NGHTTP2
  1753. if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
  1754. (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
  1755. protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
  1756. memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
  1757. NGHTTP2_PROTO_VERSION_ID_LEN);
  1758. cur += NGHTTP2_PROTO_VERSION_ID_LEN;
  1759. }
  1760. #endif
  1761. protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
  1762. memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
  1763. cur += ALPN_HTTP_1_1_LENGTH;
  1764. if(SSL_SetNextProtoNego(BACKEND->handle, protocols, cur) != SECSuccess)
  1765. goto error;
  1766. }
  1767. #endif
  1768. /* Force handshake on next I/O */
  1769. if(SSL_ResetHandshake(BACKEND->handle, /* asServer */ PR_FALSE)
  1770. != SECSuccess)
  1771. goto error;
  1772. /* propagate hostname to the TLS layer */
  1773. if(SSL_SetURL(BACKEND->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name :
  1774. conn->host.name) != SECSuccess)
  1775. goto error;
  1776. /* prevent NSS from re-using the session for a different hostname */
  1777. if(SSL_SetSockPeerID(BACKEND->handle, SSL_IS_PROXY() ?
  1778. conn->http_proxy.host.name : conn->host.name)
  1779. != SECSuccess)
  1780. goto error;
  1781. return CURLE_OK;
  1782. error:
  1783. if(model)
  1784. PR_Close(model);
  1785. return nss_fail_connect(connssl, data, result);
  1786. }
  1787. static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
  1788. {
  1789. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1790. struct Curl_easy *data = conn->data;
  1791. CURLcode result = CURLE_SSL_CONNECT_ERROR;
  1792. PRUint32 timeout;
  1793. long * const certverifyresult = SSL_IS_PROXY() ?
  1794. &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
  1795. const char * const pinnedpubkey = SSL_IS_PROXY() ?
  1796. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  1797. data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
  1798. /* check timeout situation */
  1799. const time_t time_left = Curl_timeleft(data, NULL, TRUE);
  1800. if(time_left < 0) {
  1801. failf(data, "timed out before SSL handshake");
  1802. result = CURLE_OPERATION_TIMEDOUT;
  1803. goto error;
  1804. }
  1805. /* Force the handshake now */
  1806. timeout = PR_MillisecondsToInterval((PRUint32) time_left);
  1807. if(SSL_ForceHandshakeWithTimeout(BACKEND->handle, timeout) != SECSuccess) {
  1808. if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
  1809. /* blocking direction is updated by nss_update_connecting_state() */
  1810. return CURLE_AGAIN;
  1811. else if(*certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
  1812. result = CURLE_PEER_FAILED_VERIFICATION;
  1813. else if(*certverifyresult != 0)
  1814. result = CURLE_PEER_FAILED_VERIFICATION;
  1815. goto error;
  1816. }
  1817. result = display_conn_info(conn, BACKEND->handle);
  1818. if(result)
  1819. goto error;
  1820. if(SSL_SET_OPTION(issuercert)) {
  1821. SECStatus ret = SECFailure;
  1822. char *nickname = dup_nickname(data, SSL_SET_OPTION(issuercert));
  1823. if(nickname) {
  1824. /* we support only nicknames in case of issuercert for now */
  1825. ret = check_issuer_cert(BACKEND->handle, nickname);
  1826. free(nickname);
  1827. }
  1828. if(SECFailure == ret) {
  1829. infof(data, "SSL certificate issuer check failed\n");
  1830. result = CURLE_SSL_ISSUER_ERROR;
  1831. goto error;
  1832. }
  1833. else {
  1834. infof(data, "SSL certificate issuer check ok\n");
  1835. }
  1836. }
  1837. result = cmp_peer_pubkey(connssl, pinnedpubkey);
  1838. if(result)
  1839. /* status already printed */
  1840. goto error;
  1841. return CURLE_OK;
  1842. error:
  1843. return nss_fail_connect(connssl, data, result);
  1844. }
  1845. static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
  1846. bool *done)
  1847. {
  1848. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1849. struct Curl_easy *data = conn->data;
  1850. const bool blocking = (done == NULL);
  1851. CURLcode result;
  1852. if(connssl->state == ssl_connection_complete) {
  1853. if(!blocking)
  1854. *done = TRUE;
  1855. return CURLE_OK;
  1856. }
  1857. if(connssl->connecting_state == ssl_connect_1) {
  1858. result = nss_setup_connect(conn, sockindex);
  1859. if(result)
  1860. /* we do not expect CURLE_AGAIN from nss_setup_connect() */
  1861. return result;
  1862. connssl->connecting_state = ssl_connect_2;
  1863. }
  1864. /* enable/disable blocking mode before handshake */
  1865. result = nss_set_blocking(connssl, data, blocking);
  1866. if(result)
  1867. return result;
  1868. result = nss_do_connect(conn, sockindex);
  1869. switch(result) {
  1870. case CURLE_OK:
  1871. break;
  1872. case CURLE_AGAIN:
  1873. if(!blocking)
  1874. /* CURLE_AGAIN in non-blocking mode is not an error */
  1875. return CURLE_OK;
  1876. /* FALLTHROUGH */
  1877. default:
  1878. return result;
  1879. }
  1880. if(blocking) {
  1881. /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
  1882. result = nss_set_blocking(connssl, data, /* blocking */ FALSE);
  1883. if(result)
  1884. return result;
  1885. }
  1886. else
  1887. /* signal completed SSL handshake */
  1888. *done = TRUE;
  1889. connssl->state = ssl_connection_complete;
  1890. conn->recv[sockindex] = nss_recv;
  1891. conn->send[sockindex] = nss_send;
  1892. /* ssl_connect_done is never used outside, go back to the initial state */
  1893. connssl->connecting_state = ssl_connect_1;
  1894. return CURLE_OK;
  1895. }
  1896. static CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
  1897. {
  1898. return nss_connect_common(conn, sockindex, /* blocking */ NULL);
  1899. }
  1900. static CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
  1901. int sockindex, bool *done)
  1902. {
  1903. return nss_connect_common(conn, sockindex, done);
  1904. }
  1905. static ssize_t nss_send(struct connectdata *conn, /* connection data */
  1906. int sockindex, /* socketindex */
  1907. const void *mem, /* send this data */
  1908. size_t len, /* amount to write */
  1909. CURLcode *curlcode)
  1910. {
  1911. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1912. ssize_t rc;
  1913. /* The SelectClientCert() hook uses this for infof() and failf() but the
  1914. handle stored in nss_setup_connect() could have already been freed. */
  1915. BACKEND->data = conn->data;
  1916. rc = PR_Send(BACKEND->handle, mem, (int)len, 0, PR_INTERVAL_NO_WAIT);
  1917. if(rc < 0) {
  1918. PRInt32 err = PR_GetError();
  1919. if(err == PR_WOULD_BLOCK_ERROR)
  1920. *curlcode = CURLE_AGAIN;
  1921. else {
  1922. /* print the error number and error string */
  1923. const char *err_name = nss_error_to_name(err);
  1924. infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
  1925. /* print a human-readable message describing the error if available */
  1926. nss_print_error_message(conn->data, err);
  1927. *curlcode = (is_cc_error(err))
  1928. ? CURLE_SSL_CERTPROBLEM
  1929. : CURLE_SEND_ERROR;
  1930. }
  1931. return -1;
  1932. }
  1933. return rc; /* number of bytes */
  1934. }
  1935. static ssize_t nss_recv(struct connectdata *conn, /* connection data */
  1936. int sockindex, /* socketindex */
  1937. char *buf, /* store read data here */
  1938. size_t buffersize, /* max amount to read */
  1939. CURLcode *curlcode)
  1940. {
  1941. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1942. ssize_t nread;
  1943. /* The SelectClientCert() hook uses this for infof() and failf() but the
  1944. handle stored in nss_setup_connect() could have already been freed. */
  1945. BACKEND->data = conn->data;
  1946. nread = PR_Recv(BACKEND->handle, buf, (int)buffersize, 0,
  1947. PR_INTERVAL_NO_WAIT);
  1948. if(nread < 0) {
  1949. /* failed SSL read */
  1950. PRInt32 err = PR_GetError();
  1951. if(err == PR_WOULD_BLOCK_ERROR)
  1952. *curlcode = CURLE_AGAIN;
  1953. else {
  1954. /* print the error number and error string */
  1955. const char *err_name = nss_error_to_name(err);
  1956. infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
  1957. /* print a human-readable message describing the error if available */
  1958. nss_print_error_message(conn->data, err);
  1959. *curlcode = (is_cc_error(err))
  1960. ? CURLE_SSL_CERTPROBLEM
  1961. : CURLE_RECV_ERROR;
  1962. }
  1963. return -1;
  1964. }
  1965. return nread;
  1966. }
  1967. static size_t Curl_nss_version(char *buffer, size_t size)
  1968. {
  1969. return msnprintf(buffer, size, "NSS/%s", NSS_VERSION);
  1970. }
  1971. /* data might be NULL */
  1972. static int Curl_nss_seed(struct Curl_easy *data)
  1973. {
  1974. /* make sure that NSS is initialized */
  1975. return !!Curl_nss_force_init(data);
  1976. }
  1977. /* data might be NULL */
  1978. static CURLcode Curl_nss_random(struct Curl_easy *data,
  1979. unsigned char *entropy,
  1980. size_t length)
  1981. {
  1982. Curl_nss_seed(data); /* Initiate the seed if not already done */
  1983. if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
  1984. /* signal a failure */
  1985. return CURLE_FAILED_INIT;
  1986. return CURLE_OK;
  1987. }
  1988. static CURLcode Curl_nss_md5sum(unsigned char *tmp, /* input */
  1989. size_t tmplen,
  1990. unsigned char *md5sum, /* output */
  1991. size_t md5len)
  1992. {
  1993. PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
  1994. unsigned int MD5out;
  1995. PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
  1996. PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
  1997. PK11_DestroyContext(MD5pw, PR_TRUE);
  1998. return CURLE_OK;
  1999. }
  2000. static CURLcode Curl_nss_sha256sum(const unsigned char *tmp, /* input */
  2001. size_t tmplen,
  2002. unsigned char *sha256sum, /* output */
  2003. size_t sha256len)
  2004. {
  2005. PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
  2006. unsigned int SHA256out;
  2007. PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
  2008. PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
  2009. PK11_DestroyContext(SHA256pw, PR_TRUE);
  2010. return CURLE_OK;
  2011. }
  2012. static bool Curl_nss_cert_status_request(void)
  2013. {
  2014. #ifdef SSL_ENABLE_OCSP_STAPLING
  2015. return TRUE;
  2016. #else
  2017. return FALSE;
  2018. #endif
  2019. }
  2020. static bool Curl_nss_false_start(void)
  2021. {
  2022. #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
  2023. return TRUE;
  2024. #else
  2025. return FALSE;
  2026. #endif
  2027. }
  2028. static void *Curl_nss_get_internals(struct ssl_connect_data *connssl,
  2029. CURLINFO info UNUSED_PARAM)
  2030. {
  2031. (void)info;
  2032. return BACKEND->handle;
  2033. }
  2034. const struct Curl_ssl Curl_ssl_nss = {
  2035. { CURLSSLBACKEND_NSS, "nss" }, /* info */
  2036. SSLSUPP_CA_PATH |
  2037. SSLSUPP_CERTINFO |
  2038. SSLSUPP_PINNEDPUBKEY |
  2039. SSLSUPP_HTTPS_PROXY,
  2040. sizeof(struct ssl_backend_data),
  2041. Curl_nss_init, /* init */
  2042. Curl_nss_cleanup, /* cleanup */
  2043. Curl_nss_version, /* version */
  2044. Curl_nss_check_cxn, /* check_cxn */
  2045. /* NSS has no shutdown function provided and thus always fail */
  2046. Curl_none_shutdown, /* shutdown */
  2047. Curl_none_data_pending, /* data_pending */
  2048. Curl_nss_random, /* random */
  2049. Curl_nss_cert_status_request, /* cert_status_request */
  2050. Curl_nss_connect, /* connect */
  2051. Curl_nss_connect_nonblocking, /* connect_nonblocking */
  2052. Curl_nss_get_internals, /* get_internals */
  2053. Curl_nss_close, /* close_one */
  2054. Curl_none_close_all, /* close_all */
  2055. /* NSS has its own session ID cache */
  2056. Curl_none_session_free, /* session_free */
  2057. Curl_none_set_engine, /* set_engine */
  2058. Curl_none_set_engine_default, /* set_engine_default */
  2059. Curl_none_engines_list, /* engines_list */
  2060. Curl_nss_false_start, /* false_start */
  2061. Curl_nss_md5sum, /* md5sum */
  2062. Curl_nss_sha256sum /* sha256sum */
  2063. };
  2064. #endif /* USE_NSS */