nss.c 74 KB

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