nss.c 61 KB

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