nss.c 71 KB

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