nss.c 57 KB

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