nss.c 70 KB

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