nss.c 55 KB

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