nss.c 73 KB

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