2
0

nss.c 76 KB

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