nss.c 68 KB

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