2
0

nss.c 41 KB

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