nss.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2009, 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. * $Id$
  22. ***************************************************************************/
  23. /*
  24. * Source file for all NSS-specific code for the TLS/SSL layer. No code
  25. * but sslgen.c should ever call or use these functions.
  26. */
  27. #include "setup.h"
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <ctype.h>
  31. #ifdef HAVE_SYS_SOCKET_H
  32. #include <sys/socket.h>
  33. #endif
  34. #include "urldata.h"
  35. #include "sendf.h"
  36. #include "formdata.h" /* for the boundary function */
  37. #include "url.h" /* for the ssl config check function */
  38. #include "connect.h"
  39. #include "strequal.h"
  40. #include "select.h"
  41. #include "sslgen.h"
  42. #define _MPRINTF_REPLACE /* use the internal *printf() functions */
  43. #include <curl/mprintf.h>
  44. #ifdef USE_NSS
  45. #include "nssg.h"
  46. #include <nspr.h>
  47. #include <nss.h>
  48. #include <ssl.h>
  49. #include <sslerr.h>
  50. #include <secerr.h>
  51. #include <secmod.h>
  52. #include <sslproto.h>
  53. #include <prtypes.h>
  54. #include <pk11pub.h>
  55. #include <prio.h>
  56. #include <secitem.h>
  57. #include <secport.h>
  58. #include <certdb.h>
  59. #include <base64.h>
  60. #include "curl_memory.h"
  61. #include "rawstr.h"
  62. #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
  63. /* The last #include file should be: */
  64. #include "memdebug.h"
  65. #define SSL_DIR "/etc/pki/nssdb"
  66. /* enough to fit the string "PEM Token #[0|1]" */
  67. #define SLOTSIZE 13
  68. PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
  69. PRLock * nss_initlock = NULL;
  70. volatile int initialized = 0;
  71. typedef struct {
  72. const char *name;
  73. int num;
  74. PRInt32 version; /* protocol version valid for this cipher */
  75. } cipher_s;
  76. #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
  77. (x)->pValue=(v); (x)->ulValueLen = (l)
  78. #define CERT_NewTempCertificate __CERT_NewTempCertificate
  79. enum sslversion { SSL2 = 1, SSL3 = 2, TLS = 4 };
  80. #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
  81. static const cipher_s cipherlist[] = {
  82. /* SSL2 cipher suites */
  83. {"rc4", SSL_EN_RC4_128_WITH_MD5, SSL2},
  84. {"rc4-md5", SSL_EN_RC4_128_WITH_MD5, SSL2},
  85. {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL2},
  86. {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5, SSL2},
  87. {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL2},
  88. {"des", SSL_EN_DES_64_CBC_WITH_MD5, SSL2},
  89. {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL2},
  90. /* SSL3/TLS cipher suites */
  91. {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5, SSL3 | TLS},
  92. {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA, SSL3 | TLS},
  93. {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
  94. {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA, SSL3 | TLS},
  95. {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL3 | TLS},
  96. {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL3 | TLS},
  97. {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5, SSL3 | TLS},
  98. {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA, SSL3 | TLS},
  99. {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
  100. {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL3 | TLS},
  101. {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, SSL3 | TLS},
  102. {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, SSL3 | TLS},
  103. {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA, SSL3 | TLS},
  104. /* TLS 1.0: Exportable 56-bit Cipher Suites. */
  105. {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL3 | TLS},
  106. {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL3 | TLS},
  107. /* AES ciphers. */
  108. {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA, SSL3 | TLS},
  109. {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA, SSL3 | TLS},
  110. #ifdef NSS_ENABLE_ECC
  111. /* ECC ciphers. */
  112. {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA, TLS},
  113. {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS},
  114. {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
  115. {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS},
  116. {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS},
  117. {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS},
  118. {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS},
  119. {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
  120. {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS},
  121. {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS},
  122. {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA, TLS},
  123. {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS},
  124. {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
  125. {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS},
  126. {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS},
  127. {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA, TLS},
  128. {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS},
  129. {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
  130. {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS},
  131. {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS},
  132. {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA, TLS},
  133. {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA, TLS},
  134. {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, TLS},
  135. {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS},
  136. {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA, TLS},
  137. #endif
  138. };
  139. /* following ciphers are new in NSS 3.4 and not enabled by default, therefore
  140. they are enabled explicitly */
  141. static const int enable_ciphers_by_default[] = {
  142. TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
  143. TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
  144. TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
  145. TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
  146. TLS_RSA_WITH_AES_128_CBC_SHA,
  147. TLS_RSA_WITH_AES_256_CBC_SHA,
  148. SSL_NULL_WITH_NULL_NULL
  149. };
  150. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  151. static const char* pem_library = "libnsspem.so";
  152. #endif
  153. SECMODModule* mod = NULL;
  154. static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
  155. char *cipher_list)
  156. {
  157. unsigned int i;
  158. PRBool cipher_state[NUM_OF_CIPHERS];
  159. PRBool found;
  160. char *cipher;
  161. SECStatus rv;
  162. /* First disable all ciphers. This uses a different max value in case
  163. * NSS adds more ciphers later we don't want them available by
  164. * accident
  165. */
  166. for(i=0; i<SSL_NumImplementedCiphers; i++) {
  167. SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
  168. }
  169. /* Set every entry in our list to false */
  170. for(i=0; i<NUM_OF_CIPHERS; i++) {
  171. cipher_state[i] = PR_FALSE;
  172. }
  173. cipher = cipher_list;
  174. while(cipher_list && (cipher_list[0])) {
  175. while((*cipher) && (ISSPACE(*cipher)))
  176. ++cipher;
  177. if((cipher_list = strchr(cipher, ','))) {
  178. *cipher_list++ = '\0';
  179. }
  180. found = PR_FALSE;
  181. for(i=0; i<NUM_OF_CIPHERS; i++) {
  182. if(Curl_raw_equal(cipher, cipherlist[i].name)) {
  183. cipher_state[i] = PR_TRUE;
  184. found = PR_TRUE;
  185. break;
  186. }
  187. }
  188. if(found == PR_FALSE) {
  189. failf(data, "Unknown cipher in list: %s", cipher);
  190. return SECFailure;
  191. }
  192. if(cipher_list) {
  193. cipher = cipher_list;
  194. }
  195. }
  196. /* Finally actually enable the selected ciphers */
  197. for(i=0; i<NUM_OF_CIPHERS; i++) {
  198. rv = SSL_CipherPrefSet(model, cipherlist[i].num, cipher_state[i]);
  199. if(rv != SECSuccess) {
  200. failf(data, "Unknown cipher in cipher list");
  201. return SECFailure;
  202. }
  203. }
  204. return SECSuccess;
  205. }
  206. /*
  207. * Get the number of ciphers that are enabled. We use this to determine
  208. * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
  209. */
  210. static int num_enabled_ciphers(void)
  211. {
  212. PRInt32 policy = 0;
  213. int count = 0;
  214. unsigned int i;
  215. for(i=0; i<NUM_OF_CIPHERS; i++) {
  216. SSL_CipherPolicyGet(cipherlist[i].num, &policy);
  217. if(policy)
  218. count++;
  219. }
  220. return count;
  221. }
  222. /*
  223. * Determine whether the nickname passed in is a filename that needs to
  224. * be loaded as a PEM or a regular NSS nickname.
  225. *
  226. * returns 1 for a file
  227. * returns 0 for not a file (NSS nickname)
  228. */
  229. static int is_file(const char *filename)
  230. {
  231. struct_stat st;
  232. if(filename == NULL)
  233. return 0;
  234. if(stat(filename, &st) == 0)
  235. if(S_ISREG(st.st_mode))
  236. return 1;
  237. return 0;
  238. }
  239. static char *fmt_nickname(char *str, bool *nickname_alloc)
  240. {
  241. char *nickname = NULL;
  242. *nickname_alloc = FALSE;
  243. if(is_file(str)) {
  244. char *n = strrchr(str, '/');
  245. if(n) {
  246. *nickname_alloc = TRUE;
  247. n++; /* skip last slash */
  248. nickname = aprintf("PEM Token #%d:%s", 1, n);
  249. }
  250. return nickname;
  251. }
  252. return str;
  253. }
  254. static int nss_load_cert(struct ssl_connect_data *ssl,
  255. const char *filename, PRBool cacert)
  256. {
  257. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  258. CK_SLOT_ID slotID;
  259. PK11SlotInfo * slot = NULL;
  260. CK_ATTRIBUTE *attrs;
  261. CK_ATTRIBUTE theTemplate[20];
  262. CK_BBOOL cktrue = CK_TRUE;
  263. CK_BBOOL ckfalse = CK_FALSE;
  264. CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
  265. char slotname[SLOTSIZE];
  266. #endif
  267. CERTCertificate *cert;
  268. char *nickname = NULL;
  269. char *n = NULL;
  270. /* If there is no slash in the filename it is assumed to be a regular
  271. * NSS nickname.
  272. */
  273. if(is_file(filename)) {
  274. n = strrchr(filename, '/');
  275. if(n)
  276. n++;
  277. if(!mod)
  278. return 1;
  279. }
  280. else {
  281. /* A nickname from the NSS internal database */
  282. if(cacert)
  283. return 0; /* You can't specify an NSS CA nickname this way */
  284. nickname = strdup(filename);
  285. if(!nickname)
  286. return 0;
  287. goto done;
  288. }
  289. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  290. attrs = theTemplate;
  291. /* All CA and trust objects go into slot 0. Other slots are used
  292. * for storing certificates. With each new user certificate we increment
  293. * the slot count. We only support 1 user certificate right now.
  294. */
  295. if(cacert)
  296. slotID = 0;
  297. else
  298. slotID = 1;
  299. snprintf(slotname, SLOTSIZE, "PEM Token #%ld", slotID);
  300. nickname = aprintf("PEM Token #%ld:%s", slotID, n);
  301. if(!nickname)
  302. return 0;
  303. slot = PK11_FindSlotByName(slotname);
  304. if(!slot) {
  305. free(nickname);
  306. return 0;
  307. }
  308. PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) );
  309. attrs++;
  310. PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) );
  311. attrs++;
  312. PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)filename,
  313. strlen(filename)+1);
  314. attrs++;
  315. if(cacert) {
  316. PK11_SETATTRS(attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) );
  317. }
  318. else {
  319. PK11_SETATTRS(attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) );
  320. }
  321. attrs++;
  322. /* This load the certificate in our PEM module into the appropriate
  323. * slot.
  324. */
  325. ssl->cacert[slotID] = PK11_CreateGenericObject(slot, theTemplate, 4,
  326. PR_FALSE /* isPerm */);
  327. PK11_FreeSlot(slot);
  328. if(ssl->cacert[slotID] == NULL) {
  329. free(nickname);
  330. return 0;
  331. }
  332. #else
  333. /* We don't have PK11_CreateGenericObject but a file-based cert was passed
  334. * in. We need to fail.
  335. */
  336. return 0;
  337. #endif
  338. done:
  339. /* Double-check that the certificate or nickname requested exists in
  340. * either the token or the NSS certificate database.
  341. */
  342. if(!cacert) {
  343. cert = PK11_FindCertFromNickname((char *)nickname, NULL);
  344. /* An invalid nickname was passed in */
  345. if(cert == NULL) {
  346. free(nickname);
  347. PR_SetError(SEC_ERROR_UNKNOWN_CERT, 0);
  348. return 0;
  349. }
  350. CERT_DestroyCertificate(cert);
  351. }
  352. free(nickname);
  353. return 1;
  354. }
  355. static int nss_load_crl(const char* crlfilename, PRBool ascii)
  356. {
  357. PRFileDesc *infile;
  358. PRStatus prstat;
  359. PRFileInfo info;
  360. PRInt32 nb;
  361. int rv;
  362. SECItem crlDER;
  363. CERTSignedCrl *crl=NULL;
  364. PK11SlotInfo *slot=NULL;
  365. infile = PR_Open(crlfilename,PR_RDONLY,0);
  366. if (!infile) {
  367. return 0;
  368. }
  369. crlDER.data = NULL;
  370. prstat = PR_GetOpenFileInfo(infile,&info);
  371. if (prstat!=PR_SUCCESS)
  372. return 0;
  373. if (ascii) {
  374. SECItem filedata;
  375. char *asc,*body;
  376. filedata.data = NULL;
  377. if (!SECITEM_AllocItem(NULL,&filedata,info.size))
  378. return 0;
  379. nb = PR_Read(infile,filedata.data,info.size);
  380. if (nb!=info.size)
  381. return 0;
  382. asc = (char*)filedata.data;
  383. if (!asc)
  384. return 0;
  385. body=strstr(asc,"-----BEGIN");
  386. if (body != NULL) {
  387. char *trailer=NULL;
  388. asc = body;
  389. body = PORT_Strchr(asc,'\n');
  390. if (!body)
  391. body = PORT_Strchr(asc,'\r');
  392. if (body)
  393. trailer = strstr(++body,"-----END");
  394. if (trailer!=NULL)
  395. *trailer='\0';
  396. else
  397. return 0;
  398. }
  399. else {
  400. body = asc;
  401. }
  402. rv = ATOB_ConvertAsciiToItem(&crlDER,body);
  403. PORT_Free(filedata.data);
  404. if (rv)
  405. return 0;
  406. }
  407. else {
  408. if (!SECITEM_AllocItem(NULL,&crlDER,info.size))
  409. return 0;
  410. nb = PR_Read(infile,crlDER.data,info.size);
  411. if (nb!=info.size)
  412. return 0;
  413. }
  414. slot = PK11_GetInternalKeySlot();
  415. crl = PK11_ImportCRL(slot,&crlDER,
  416. NULL,SEC_CRL_TYPE,
  417. NULL,CRL_IMPORT_DEFAULT_OPTIONS,
  418. NULL,(CRL_DECODE_DEFAULT_OPTIONS|
  419. CRL_DECODE_DONT_COPY_DER));
  420. if (slot) PK11_FreeSlot(slot);
  421. if (!crl) return 0;
  422. SEC_DestroyCrl(crl);
  423. return 1;
  424. }
  425. static int nss_load_key(struct connectdata *conn, int sockindex, char *key_file)
  426. {
  427. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  428. PK11SlotInfo * slot = NULL;
  429. CK_ATTRIBUTE *attrs;
  430. CK_ATTRIBUTE theTemplate[20];
  431. CK_BBOOL cktrue = CK_TRUE;
  432. CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
  433. CK_SLOT_ID slotID;
  434. char slotname[SLOTSIZE];
  435. struct ssl_connect_data *sslconn = &conn->ssl[sockindex];
  436. attrs = theTemplate;
  437. /* FIXME: grok the various file types */
  438. slotID = 1; /* hardcoded for now */
  439. snprintf(slotname, sizeof(slotname), "PEM Token #%ld", slotID);
  440. slot = PK11_FindSlotByName(slotname);
  441. if(!slot)
  442. return 0;
  443. PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
  444. PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
  445. PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)key_file,
  446. strlen(key_file)+1); attrs++;
  447. /* When adding an encrypted key the PKCS#11 will be set as removed */
  448. sslconn->key = PK11_CreateGenericObject(slot, theTemplate, 3,
  449. PR_FALSE /* isPerm */);
  450. if(sslconn->key == NULL) {
  451. PR_SetError(SEC_ERROR_BAD_KEY, 0);
  452. return 0;
  453. }
  454. /* This will force the token to be seen as re-inserted */
  455. SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
  456. PK11_IsPresent(slot);
  457. /* parg is initialized in nss_Init_Tokens() */
  458. if(PK11_Authenticate(slot, PR_TRUE,
  459. conn->data->set.str[STRING_KEY_PASSWD]) != SECSuccess) {
  460. PK11_FreeSlot(slot);
  461. return 0;
  462. }
  463. PK11_FreeSlot(slot);
  464. return 1;
  465. #else
  466. /* If we don't have PK11_CreateGenericObject then we can't load a file-based
  467. * key.
  468. */
  469. (void)conn; /* unused */
  470. (void)key_file; /* unused */
  471. return 0;
  472. #endif
  473. }
  474. static int display_error(struct connectdata *conn, PRInt32 err,
  475. const char *filename)
  476. {
  477. switch(err) {
  478. case SEC_ERROR_BAD_PASSWORD:
  479. failf(conn->data, "Unable to load client key: Incorrect password");
  480. return 1;
  481. case SEC_ERROR_UNKNOWN_CERT:
  482. failf(conn->data, "Unable to load certificate %s", filename);
  483. return 1;
  484. default:
  485. break;
  486. }
  487. return 0; /* The caller will print a generic error */
  488. }
  489. static int cert_stuff(struct connectdata *conn,
  490. int sockindex, char *cert_file, char *key_file)
  491. {
  492. struct SessionHandle *data = conn->data;
  493. int rv = 0;
  494. if(cert_file) {
  495. rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
  496. if(!rv) {
  497. if(!display_error(conn, PR_GetError(), cert_file))
  498. failf(data, "Unable to load client cert %d.", PR_GetError());
  499. return 0;
  500. }
  501. }
  502. if(key_file || (is_file(cert_file))) {
  503. if(key_file)
  504. rv = nss_load_key(conn, sockindex, key_file);
  505. else
  506. /* In case the cert file also has the key */
  507. rv = nss_load_key(conn, sockindex, cert_file);
  508. if(!rv) {
  509. if(!display_error(conn, PR_GetError(), key_file))
  510. failf(data, "Unable to load client key %d.", PR_GetError());
  511. return 0;
  512. }
  513. }
  514. return 1;
  515. }
  516. static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
  517. {
  518. (void)slot; /* unused */
  519. if(retry || NULL == arg)
  520. return NULL;
  521. else
  522. return (char *)PORT_Strdup((char *)arg);
  523. }
  524. static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
  525. {
  526. SECStatus success = SECSuccess;
  527. struct connectdata *conn = (struct connectdata *)arg;
  528. PRErrorCode err = PR_GetError();
  529. CERTCertificate *cert = NULL;
  530. char *subject, *subject_cn, *issuer;
  531. if(conn->data->set.ssl.certverifyresult!=0)
  532. return success;
  533. conn->data->set.ssl.certverifyresult=err;
  534. cert = SSL_PeerCertificate(sock);
  535. subject = CERT_NameToAscii(&cert->subject);
  536. subject_cn = CERT_GetCommonName(&cert->subject);
  537. issuer = CERT_NameToAscii(&cert->issuer);
  538. CERT_DestroyCertificate(cert);
  539. switch(err) {
  540. case SEC_ERROR_CA_CERT_INVALID:
  541. infof(conn->data, "Issuer certificate is invalid: '%s'\n", issuer);
  542. if(conn->data->set.ssl.verifypeer)
  543. success = SECFailure;
  544. break;
  545. case SEC_ERROR_UNTRUSTED_ISSUER:
  546. if(conn->data->set.ssl.verifypeer)
  547. success = SECFailure;
  548. infof(conn->data, "Certificate is signed by an untrusted issuer: '%s'\n",
  549. issuer);
  550. break;
  551. case SSL_ERROR_BAD_CERT_DOMAIN:
  552. if(conn->data->set.ssl.verifyhost) {
  553. failf(conn->data, "SSL: certificate subject name '%s' does not match "
  554. "target host name '%s'", subject_cn, conn->host.dispname);
  555. success = SECFailure;
  556. } else {
  557. infof(conn->data, "warning: SSL: certificate subject name '%s' does not "
  558. "match target host name '%s'\n", subject_cn, conn->host.dispname);
  559. }
  560. break;
  561. case SEC_ERROR_EXPIRED_CERTIFICATE:
  562. if(conn->data->set.ssl.verifypeer)
  563. success = SECFailure;
  564. infof(conn->data, "Remote Certificate has expired.\n");
  565. break;
  566. case SEC_ERROR_UNKNOWN_ISSUER:
  567. if(conn->data->set.ssl.verifypeer)
  568. success = SECFailure;
  569. infof(conn->data, "Peer's certificate issuer is not recognized: '%s'\n",
  570. issuer);
  571. break;
  572. default:
  573. if(conn->data->set.ssl.verifypeer)
  574. success = SECFailure;
  575. infof(conn->data, "Bad certificate received. Subject = '%s', "
  576. "Issuer = '%s'\n", subject, issuer);
  577. break;
  578. }
  579. if(success == SECSuccess)
  580. infof(conn->data, "SSL certificate verify ok.\n");
  581. PR_Free(subject);
  582. PR_Free(subject_cn);
  583. PR_Free(issuer);
  584. return success;
  585. }
  586. /**
  587. * Inform the application that the handshake is complete.
  588. */
  589. static SECStatus HandshakeCallback(PRFileDesc *sock, void *arg)
  590. {
  591. (void)sock;
  592. (void)arg;
  593. return SECSuccess;
  594. }
  595. static void display_cert_info(struct SessionHandle *data, CERTCertificate *cert) {
  596. char *subject, *issuer, *common_name;
  597. PRExplodedTime printableTime;
  598. char timeString[256];
  599. PRTime notBefore, notAfter;
  600. subject = CERT_NameToAscii(&cert->subject);
  601. issuer = CERT_NameToAscii(&cert->issuer);
  602. common_name = CERT_GetCommonName(&cert->subject);
  603. infof(data, "\tsubject: %s\n", subject);
  604. CERT_GetCertTimes(cert, &notBefore, &notAfter);
  605. PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
  606. PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
  607. infof(data, "\tstart date: %s\n", timeString);
  608. PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
  609. PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
  610. infof(data, "\texpire date: %s\n", timeString);
  611. infof(data, "\tcommon name: %s\n", common_name);
  612. infof(data, "\tissuer: %s\n", issuer);
  613. PR_Free(subject);
  614. PR_Free(issuer);
  615. PR_Free(common_name);
  616. }
  617. static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
  618. {
  619. SSLChannelInfo channel;
  620. SSLCipherSuiteInfo suite;
  621. CERTCertificate *cert;
  622. if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
  623. SECSuccess && channel.length == sizeof channel &&
  624. channel.cipherSuite) {
  625. if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
  626. &suite, sizeof suite) == SECSuccess) {
  627. infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
  628. }
  629. }
  630. infof(conn->data, "Server certificate:\n");
  631. cert = SSL_PeerCertificate(sock);
  632. display_cert_info(conn->data, cert);
  633. CERT_DestroyCertificate(cert);
  634. return;
  635. }
  636. /**
  637. *
  638. * Check that the Peer certificate's issuer certificate matches the one found
  639. * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
  640. * issuer check, so we provide comments that mimic the OpenSSL
  641. * X509_check_issued function (in x509v3/v3_purp.c)
  642. */
  643. static SECStatus check_issuer_cert(PRFileDesc *sock,
  644. char *issuer_nickname)
  645. {
  646. CERTCertificate *cert,*cert_issuer,*issuer;
  647. SECStatus res=SECSuccess;
  648. void *proto_win = NULL;
  649. /*
  650. PRArenaPool *tmpArena = NULL;
  651. CERTAuthKeyID *authorityKeyID = NULL;
  652. SECITEM *caname = NULL;
  653. */
  654. cert = SSL_PeerCertificate(sock);
  655. cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
  656. proto_win = SSL_RevealPinArg(sock);
  657. issuer = NULL;
  658. issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
  659. if ((!cert_issuer) || (!issuer))
  660. res = SECFailure;
  661. else if (SECITEM_CompareItem(&cert_issuer->derCert,
  662. &issuer->derCert)!=SECEqual)
  663. res = SECFailure;
  664. CERT_DestroyCertificate(cert);
  665. CERT_DestroyCertificate(issuer);
  666. CERT_DestroyCertificate(cert_issuer);
  667. return res;
  668. }
  669. /**
  670. *
  671. * Callback to pick the SSL client certificate.
  672. */
  673. static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
  674. struct CERTDistNamesStr *caNames,
  675. struct CERTCertificateStr **pRetCert,
  676. struct SECKEYPrivateKeyStr **pRetKey)
  677. {
  678. static const char pem_nickname[] = "PEM Token #1";
  679. const char *pem_slotname = pem_nickname;
  680. struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
  681. struct SessionHandle *data = connssl->data;
  682. const char *nickname = connssl->client_nickname;
  683. if (mod && nickname &&
  684. 0 == strncmp(nickname, pem_nickname, /* length of "PEM Token" */ 9)) {
  685. /* use the cert/key provided by PEM reader */
  686. PK11SlotInfo *slot;
  687. void *proto_win = SSL_RevealPinArg(sock);
  688. *pRetKey = NULL;
  689. *pRetCert = PK11_FindCertFromNickname(nickname, proto_win);
  690. if (NULL == *pRetCert) {
  691. failf(data, "NSS: client certificate not found: %s", nickname);
  692. return SECFailure;
  693. }
  694. slot = PK11_FindSlotByName(pem_slotname);
  695. if (NULL == slot) {
  696. failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
  697. return SECFailure;
  698. }
  699. *pRetKey = PK11_FindPrivateKeyFromCert(slot, *pRetCert, NULL);
  700. PK11_FreeSlot(slot);
  701. if (NULL == *pRetKey) {
  702. failf(data, "NSS: private key not found for certificate: %s", nickname);
  703. return SECFailure;
  704. }
  705. infof(data, "NSS: client certificate: %s\n", nickname);
  706. display_cert_info(data, *pRetCert);
  707. return SECSuccess;
  708. }
  709. /* use the default NSS hook */
  710. if (SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
  711. pRetCert, pRetKey)
  712. || NULL == *pRetCert) {
  713. if (NULL == nickname)
  714. failf(data, "NSS: client certificate not found (nickname not specified)");
  715. else
  716. failf(data, "NSS: client certificate not found: %s", nickname);
  717. return SECFailure;
  718. }
  719. /* get certificate nickname if any */
  720. nickname = (*pRetCert)->nickname;
  721. if (NULL == nickname)
  722. nickname = "[unknown]";
  723. if (NULL == *pRetKey) {
  724. failf(data, "NSS: private key not found for certificate: %s", nickname);
  725. return SECFailure;
  726. }
  727. infof(data, "NSS: using client certificate: %s\n", nickname);
  728. display_cert_info(data, *pRetCert);
  729. return SECSuccess;
  730. }
  731. /* This function is supposed to decide, which error codes should be used
  732. * to conclude server is TLS intolerant.
  733. *
  734. * taken from xulrunner - nsNSSIOLayer.cpp
  735. */
  736. static PRBool
  737. isTLSIntoleranceError(PRInt32 err)
  738. {
  739. switch (err) {
  740. case SSL_ERROR_BAD_MAC_ALERT:
  741. case SSL_ERROR_BAD_MAC_READ:
  742. case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
  743. case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
  744. case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE:
  745. case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
  746. case SSL_ERROR_NO_CYPHER_OVERLAP:
  747. case SSL_ERROR_BAD_SERVER:
  748. case SSL_ERROR_BAD_BLOCK_PADDING:
  749. case SSL_ERROR_UNSUPPORTED_VERSION:
  750. case SSL_ERROR_PROTOCOL_VERSION_ALERT:
  751. case SSL_ERROR_RX_MALFORMED_FINISHED:
  752. case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE:
  753. case SSL_ERROR_DECODE_ERROR_ALERT:
  754. case SSL_ERROR_RX_UNKNOWN_ALERT:
  755. return PR_TRUE;
  756. default:
  757. return PR_FALSE;
  758. }
  759. }
  760. /**
  761. * Global SSL init
  762. *
  763. * @retval 0 error initializing SSL
  764. * @retval 1 SSL initialized successfully
  765. */
  766. int Curl_nss_init(void)
  767. {
  768. /* curl_global_init() is not thread-safe so this test is ok */
  769. if (nss_initlock == NULL) {
  770. PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
  771. nss_initlock = PR_NewLock();
  772. }
  773. /* We will actually initialize NSS later */
  774. return 1;
  775. }
  776. /* Global cleanup */
  777. void Curl_nss_cleanup(void)
  778. {
  779. /* This function isn't required to be threadsafe and this is only done
  780. * as a safety feature.
  781. */
  782. PR_Lock(nss_initlock);
  783. if (initialized) {
  784. /* Free references to client certificates held in the SSL session cache.
  785. * Omitting this hampers destruction of the security module owning
  786. * the certificates. */
  787. SSL_ClearSessionCache();
  788. if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
  789. SECMOD_DestroyModule(mod);
  790. mod = NULL;
  791. }
  792. NSS_Shutdown();
  793. }
  794. PR_Unlock(nss_initlock);
  795. PR_DestroyLock(nss_initlock);
  796. nss_initlock = NULL;
  797. initialized = 0;
  798. }
  799. /*
  800. * This function uses SSL_peek to determine connection status.
  801. *
  802. * Return codes:
  803. * 1 means the connection is still in place
  804. * 0 means the connection has been closed
  805. * -1 means the connection status is unknown
  806. */
  807. int
  808. Curl_nss_check_cxn(struct connectdata *conn)
  809. {
  810. int rc;
  811. char buf;
  812. rc =
  813. PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
  814. PR_SecondsToInterval(1));
  815. if(rc > 0)
  816. return 1; /* connection still in place */
  817. if(rc == 0)
  818. return 0; /* connection has been closed */
  819. return -1; /* connection status unknown */
  820. }
  821. /*
  822. * This function is called when an SSL connection is closed.
  823. */
  824. void Curl_nss_close(struct connectdata *conn, int sockindex)
  825. {
  826. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  827. if(connssl->handle) {
  828. PR_Close(connssl->handle);
  829. /* NSS closes the socket we previously handed to it, so we must mark it
  830. as closed to avoid double close */
  831. fake_sclose(conn->sock[sockindex]);
  832. conn->sock[sockindex] = CURL_SOCKET_BAD;
  833. if(connssl->client_nickname != NULL) {
  834. free(connssl->client_nickname);
  835. connssl->client_nickname = NULL;
  836. }
  837. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  838. if(connssl->key)
  839. (void)PK11_DestroyGenericObject(connssl->key);
  840. if(connssl->cacert[1])
  841. (void)PK11_DestroyGenericObject(connssl->cacert[1]);
  842. if(connssl->cacert[0])
  843. (void)PK11_DestroyGenericObject(connssl->cacert[0]);
  844. #endif
  845. connssl->handle = NULL;
  846. }
  847. }
  848. /*
  849. * This function is called when the 'data' struct is going away. Close
  850. * down everything and free all resources!
  851. */
  852. int Curl_nss_close_all(struct SessionHandle *data)
  853. {
  854. (void)data;
  855. return 0;
  856. }
  857. CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
  858. {
  859. PRInt32 err;
  860. PRFileDesc *model = NULL;
  861. PRBool ssl2 = PR_FALSE;
  862. PRBool ssl3 = PR_FALSE;
  863. PRBool tlsv1 = PR_FALSE;
  864. struct SessionHandle *data = conn->data;
  865. curl_socket_t sockfd = conn->sock[sockindex];
  866. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  867. SECStatus rv;
  868. char *certDir = NULL;
  869. int curlerr;
  870. const int *cipher_to_enable;
  871. PRSocketOptionData sock_opt;
  872. PRUint32 timeout;
  873. curlerr = CURLE_SSL_CONNECT_ERROR;
  874. if (connssl->state == ssl_connection_complete)
  875. return CURLE_OK;
  876. connssl->data = data;
  877. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  878. connssl->cacert[0] = NULL;
  879. connssl->cacert[1] = NULL;
  880. connssl->key = NULL;
  881. #endif
  882. /* FIXME. NSS doesn't support multiple databases open at the same time. */
  883. PR_Lock(nss_initlock);
  884. if(!initialized) {
  885. struct_stat st;
  886. /* First we check if $SSL_DIR points to a valid dir */
  887. certDir = getenv("SSL_DIR");
  888. if(certDir) {
  889. if((stat(certDir, &st) != 0) ||
  890. (!S_ISDIR(st.st_mode))) {
  891. certDir = NULL;
  892. }
  893. }
  894. /* Now we check if the default location is a valid dir */
  895. if(!certDir) {
  896. if((stat(SSL_DIR, &st) == 0) &&
  897. (S_ISDIR(st.st_mode))) {
  898. certDir = (char *)SSL_DIR;
  899. }
  900. }
  901. if (!NSS_IsInitialized()) {
  902. initialized = 1;
  903. infof(conn->data, "Initializing NSS with certpath: %s\n",
  904. certDir ? certDir : "none");
  905. if(!certDir) {
  906. rv = NSS_NoDB_Init(NULL);
  907. }
  908. else {
  909. char *certpath = PR_smprintf("%s%s",
  910. NSS_VersionCheck("3.12.0") ? "sql:" : "",
  911. certDir);
  912. rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY);
  913. PR_smprintf_free(certpath);
  914. }
  915. if(rv != SECSuccess) {
  916. infof(conn->data, "Unable to initialize NSS database\n");
  917. curlerr = CURLE_SSL_CACERT_BADFILE;
  918. initialized = 0;
  919. PR_Unlock(nss_initlock);
  920. goto error;
  921. }
  922. }
  923. if(num_enabled_ciphers() == 0)
  924. NSS_SetDomesticPolicy();
  925. #ifdef HAVE_PK11_CREATEGENERICOBJECT
  926. if(!mod) {
  927. char *configstring = aprintf("library=%s name=PEM", pem_library);
  928. if(!configstring) {
  929. PR_Unlock(nss_initlock);
  930. goto error;
  931. }
  932. mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
  933. free(configstring);
  934. if(!mod || !mod->loaded) {
  935. if(mod) {
  936. SECMOD_DestroyModule(mod);
  937. mod = NULL;
  938. }
  939. infof(data, "WARNING: failed to load NSS PEM library %s. Using OpenSSL "
  940. "PEM certificates will not work.\n", pem_library);
  941. }
  942. }
  943. #endif
  944. PK11_SetPasswordFunc(nss_get_password);
  945. }
  946. PR_Unlock(nss_initlock);
  947. model = PR_NewTCPSocket();
  948. if(!model)
  949. goto error;
  950. model = SSL_ImportFD(NULL, model);
  951. /* make the socket nonblocking */
  952. sock_opt.option = PR_SockOpt_Nonblocking;
  953. sock_opt.value.non_blocking = PR_TRUE;
  954. if(PR_SetSocketOption(model, &sock_opt) != SECSuccess)
  955. goto error;
  956. if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
  957. goto error;
  958. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
  959. goto error;
  960. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
  961. goto error;
  962. switch (data->set.ssl.version) {
  963. default:
  964. case CURL_SSLVERSION_DEFAULT:
  965. ssl3 = PR_TRUE;
  966. if (data->state.ssl_connect_retry)
  967. infof(data, "TLS disabled due to previous handshake failure\n");
  968. else
  969. tlsv1 = PR_TRUE;
  970. break;
  971. case CURL_SSLVERSION_TLSv1:
  972. tlsv1 = PR_TRUE;
  973. break;
  974. case CURL_SSLVERSION_SSLv2:
  975. ssl2 = PR_TRUE;
  976. break;
  977. case CURL_SSLVERSION_SSLv3:
  978. ssl3 = PR_TRUE;
  979. break;
  980. }
  981. if(SSL_OptionSet(model, SSL_ENABLE_SSL2, ssl2) != SECSuccess)
  982. goto error;
  983. if(SSL_OptionSet(model, SSL_ENABLE_SSL3, ssl3) != SECSuccess)
  984. goto error;
  985. if(SSL_OptionSet(model, SSL_ENABLE_TLS, tlsv1) != SECSuccess)
  986. goto error;
  987. if(SSL_OptionSet(model, SSL_V2_COMPATIBLE_HELLO, ssl2) != SECSuccess)
  988. goto error;
  989. /* reset the flag to avoid an infinite loop */
  990. data->state.ssl_connect_retry = FALSE;
  991. /* enable all ciphers from enable_ciphers_by_default */
  992. cipher_to_enable = enable_ciphers_by_default;
  993. while (SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
  994. if (SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
  995. curlerr = CURLE_SSL_CIPHER;
  996. goto error;
  997. }
  998. cipher_to_enable++;
  999. }
  1000. if(data->set.ssl.cipher_list) {
  1001. if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
  1002. curlerr = CURLE_SSL_CIPHER;
  1003. goto error;
  1004. }
  1005. }
  1006. if(data->set.ssl.verifyhost == 1)
  1007. infof(data, "warning: ignoring unsupported value (1) of ssl.verifyhost\n");
  1008. data->set.ssl.certverifyresult=0; /* not checked yet */
  1009. if(SSL_BadCertHook(model, (SSLBadCertHandler) BadCertHandler, conn)
  1010. != SECSuccess) {
  1011. goto error;
  1012. }
  1013. if(SSL_HandshakeCallback(model, (SSLHandshakeCallback) HandshakeCallback,
  1014. NULL) != SECSuccess)
  1015. goto error;
  1016. if(!data->set.ssl.verifypeer)
  1017. /* skip the verifying of the peer */
  1018. ;
  1019. else if(data->set.ssl.CAfile) {
  1020. int rc = nss_load_cert(&conn->ssl[sockindex], data->set.ssl.CAfile,
  1021. PR_TRUE);
  1022. if(!rc) {
  1023. curlerr = CURLE_SSL_CACERT_BADFILE;
  1024. goto error;
  1025. }
  1026. }
  1027. else if(data->set.ssl.CApath) {
  1028. struct_stat st;
  1029. PRDir *dir;
  1030. PRDirEntry *entry;
  1031. if(stat(data->set.ssl.CApath, &st) == -1) {
  1032. curlerr = CURLE_SSL_CACERT_BADFILE;
  1033. goto error;
  1034. }
  1035. if(S_ISDIR(st.st_mode)) {
  1036. int rc;
  1037. dir = PR_OpenDir(data->set.ssl.CApath);
  1038. do {
  1039. entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN);
  1040. if(entry) {
  1041. char fullpath[PATH_MAX];
  1042. snprintf(fullpath, sizeof(fullpath), "%s/%s", data->set.ssl.CApath,
  1043. entry->name);
  1044. rc = nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE);
  1045. /* FIXME: check this return value! */
  1046. }
  1047. /* This is purposefully tolerant of errors so non-PEM files
  1048. * can be in the same directory */
  1049. } while(entry != NULL);
  1050. PR_CloseDir(dir);
  1051. }
  1052. }
  1053. infof(data,
  1054. " CAfile: %s\n"
  1055. " CApath: %s\n",
  1056. data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
  1057. data->set.ssl.CApath ? data->set.ssl.CApath : "none");
  1058. if (data->set.ssl.CRLfile) {
  1059. int rc = nss_load_crl(data->set.ssl.CRLfile, PR_FALSE);
  1060. if (!rc) {
  1061. curlerr = CURLE_SSL_CRL_BADFILE;
  1062. goto error;
  1063. }
  1064. infof(data,
  1065. " CRLfile: %s\n",
  1066. data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
  1067. }
  1068. if(data->set.str[STRING_CERT]) {
  1069. bool nickname_alloc = FALSE;
  1070. char *nickname = fmt_nickname(data->set.str[STRING_CERT], &nickname_alloc);
  1071. if(!nickname)
  1072. return CURLE_OUT_OF_MEMORY;
  1073. if(!cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
  1074. data->set.str[STRING_KEY])) {
  1075. /* failf() is already done in cert_stuff() */
  1076. if(nickname_alloc)
  1077. free(nickname);
  1078. return CURLE_SSL_CERTPROBLEM;
  1079. }
  1080. /* this "takes over" the pointer to the allocated name or makes a
  1081. dup of it */
  1082. connssl->client_nickname = nickname_alloc?nickname:strdup(nickname);
  1083. if(!connssl->client_nickname)
  1084. return CURLE_OUT_OF_MEMORY;
  1085. }
  1086. else
  1087. connssl->client_nickname = NULL;
  1088. if(SSL_GetClientAuthDataHook(model, SelectClientCert,
  1089. (void *)connssl) != SECSuccess) {
  1090. curlerr = CURLE_SSL_CERTPROBLEM;
  1091. goto error;
  1092. }
  1093. /* Import our model socket onto the existing file descriptor */
  1094. connssl->handle = PR_ImportTCPSocket(sockfd);
  1095. connssl->handle = SSL_ImportFD(model, connssl->handle);
  1096. if(!connssl->handle)
  1097. goto error;
  1098. PR_Close(model); /* We don't need this any more */
  1099. model = NULL;
  1100. /* This is the password associated with the cert that we're using */
  1101. if (data->set.str[STRING_KEY_PASSWD]) {
  1102. SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
  1103. }
  1104. /* Force handshake on next I/O */
  1105. SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
  1106. SSL_SetURL(connssl->handle, conn->host.name);
  1107. /* Force the handshake now */
  1108. timeout = PR_MillisecondsToInterval(Curl_timeleft(conn, NULL, TRUE));
  1109. if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
  1110. if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
  1111. curlerr = CURLE_PEER_FAILED_VERIFICATION;
  1112. else if(conn->data->set.ssl.certverifyresult!=0)
  1113. curlerr = CURLE_SSL_CACERT;
  1114. goto error;
  1115. }
  1116. connssl->state = ssl_connection_complete;
  1117. display_conn_info(conn, connssl->handle);
  1118. if (data->set.str[STRING_SSL_ISSUERCERT]) {
  1119. SECStatus ret;
  1120. bool nickname_alloc = FALSE;
  1121. char *nickname = fmt_nickname(data->set.str[STRING_SSL_ISSUERCERT],
  1122. &nickname_alloc);
  1123. if(!nickname)
  1124. return CURLE_OUT_OF_MEMORY;
  1125. ret = check_issuer_cert(connssl->handle, nickname);
  1126. if(nickname_alloc)
  1127. free(nickname);
  1128. if(SECFailure == ret) {
  1129. infof(data,"SSL certificate issuer check failed\n");
  1130. curlerr = CURLE_SSL_ISSUER_ERROR;
  1131. goto error;
  1132. }
  1133. else {
  1134. infof(data, "SSL certificate issuer check ok\n");
  1135. }
  1136. }
  1137. return CURLE_OK;
  1138. error:
  1139. /* reset the flag to avoid an infinite loop */
  1140. data->state.ssl_connect_retry = FALSE;
  1141. err = PR_GetError();
  1142. infof(data, "NSS error %d\n", err);
  1143. if(model)
  1144. PR_Close(model);
  1145. if (ssl3 && tlsv1 && isTLSIntoleranceError(err)) {
  1146. /* schedule reconnect through Curl_retry_request() */
  1147. data->state.ssl_connect_retry = TRUE;
  1148. infof(data, "Error in TLS handshake, trying SSLv3...\n");
  1149. return CURLE_OK;
  1150. }
  1151. return curlerr;
  1152. }
  1153. /* return number of sent (non-SSL) bytes */
  1154. int Curl_nss_send(struct connectdata *conn, /* connection data */
  1155. int sockindex, /* socketindex */
  1156. const void *mem, /* send this data */
  1157. size_t len) /* amount to write */
  1158. {
  1159. int rc;
  1160. rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0, -1);
  1161. if(rc < 0) {
  1162. failf(conn->data, "SSL write: error %d", PR_GetError());
  1163. return -1;
  1164. }
  1165. return rc; /* number of bytes */
  1166. }
  1167. /*
  1168. * If the read would block we return -1 and set 'wouldblock' to TRUE.
  1169. * Otherwise we return the amount of data read. Other errors should return -1
  1170. * and set 'wouldblock' to FALSE.
  1171. */
  1172. ssize_t Curl_nss_recv(struct connectdata * conn, /* connection data */
  1173. int num, /* socketindex */
  1174. char *buf, /* store read data here */
  1175. size_t buffersize, /* max amount to read */
  1176. bool * wouldblock)
  1177. {
  1178. ssize_t nread;
  1179. nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0, -1);
  1180. *wouldblock = FALSE;
  1181. if(nread < 0) {
  1182. /* failed SSL read */
  1183. PRInt32 err = PR_GetError();
  1184. if(err == PR_WOULD_BLOCK_ERROR) {
  1185. *wouldblock = TRUE;
  1186. return -1; /* basically EWOULDBLOCK */
  1187. }
  1188. failf(conn->data, "SSL read: errno %d", err);
  1189. return -1;
  1190. }
  1191. return nread;
  1192. }
  1193. size_t Curl_nss_version(char *buffer, size_t size)
  1194. {
  1195. return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
  1196. }
  1197. #endif /* USE_NSS */