nss.c 75 KB

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