nss.c 76 KB

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