nss.c 37 KB

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