nss.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, Daniel Stenberg, <[email protected]>, 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 result = (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 result;
  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 result;
  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 result = (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. result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
  358. if(!result && !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 result;
  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 result;
  465. struct ssl_connect_data *ssl = conn->ssl;
  466. (void)sockindex; /* unused */
  467. result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
  468. if(result) {
  469. PR_SetError(SEC_ERROR_BAD_KEY, 0);
  470. return result;
  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) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
  482. }
  483. static int display_error(struct connectdata *conn, PRInt32 err,
  484. const char *filename)
  485. {
  486. switch(err) {
  487. case SEC_ERROR_BAD_PASSWORD:
  488. failf(conn->data, "Unable to load client key: Incorrect password");
  489. return 1;
  490. case SEC_ERROR_UNKNOWN_CERT:
  491. failf(conn->data, "Unable to load certificate %s", filename);
  492. return 1;
  493. default:
  494. break;
  495. }
  496. return 0; /* The caller will print a generic error */
  497. }
  498. static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
  499. char *cert_file, char *key_file)
  500. {
  501. struct SessionHandle *data = conn->data;
  502. CURLcode result;
  503. if(cert_file) {
  504. result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
  505. if(result) {
  506. const PRErrorCode err = PR_GetError();
  507. if(!display_error(conn, err, cert_file)) {
  508. const char *err_name = nss_error_to_name(err);
  509. failf(data, "unable to load client cert: %d (%s)", err, err_name);
  510. }
  511. return result;
  512. }
  513. }
  514. if(key_file || (is_file(cert_file))) {
  515. if(key_file)
  516. result = nss_load_key(conn, sockindex, key_file);
  517. else
  518. /* In case the cert file also has the key */
  519. result = nss_load_key(conn, sockindex, cert_file);
  520. if(result) {
  521. const PRErrorCode err = PR_GetError();
  522. if(!display_error(conn, err, key_file)) {
  523. const char *err_name = nss_error_to_name(err);
  524. failf(data, "unable to load client key: %d (%s)", err, err_name);
  525. }
  526. return result;
  527. }
  528. }
  529. return CURLE_OK;
  530. }
  531. static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
  532. {
  533. (void)slot; /* unused */
  534. if(retry || NULL == arg)
  535. return NULL;
  536. else
  537. return (char *)PORT_Strdup((char *)arg);
  538. }
  539. /* bypass the default SSL_AuthCertificate() hook in case we do not want to
  540. * verify peer */
  541. static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
  542. PRBool isServer)
  543. {
  544. struct connectdata *conn = (struct connectdata *)arg;
  545. if(!conn->data->set.ssl.verifypeer) {
  546. infof(conn->data, "skipping SSL peer certificate verification\n");
  547. return SECSuccess;
  548. }
  549. return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
  550. }
  551. /**
  552. * Inform the application that the handshake is complete.
  553. */
  554. static void HandshakeCallback(PRFileDesc *sock, void *arg)
  555. {
  556. #ifdef USE_NGHTTP2
  557. struct connectdata *conn = (struct connectdata*) arg;
  558. unsigned int buflenmax = 50;
  559. unsigned char buf[50];
  560. unsigned int buflen;
  561. SSLNextProtoState state;
  562. if(!conn->data->set.ssl_enable_npn && !conn->data->set.ssl_enable_alpn) {
  563. return;
  564. }
  565. if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
  566. switch(state) {
  567. case SSL_NEXT_PROTO_NO_SUPPORT:
  568. case SSL_NEXT_PROTO_NO_OVERLAP:
  569. if(connssl->asked_for_h2)
  570. infof(conn->data, "TLS, neither ALPN nor NPN succeeded\n");
  571. return;
  572. #ifdef SSL_ENABLE_ALPN
  573. case SSL_NEXT_PROTO_SELECTED:
  574. infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
  575. break;
  576. #endif
  577. case SSL_NEXT_PROTO_NEGOTIATED:
  578. infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
  579. break;
  580. }
  581. if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
  582. memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)
  583. == 0) {
  584. conn->negnpn = NPN_HTTP2;
  585. }
  586. else if(buflen == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1, buf,
  587. ALPN_HTTP_1_1_LENGTH)) {
  588. conn->negnpn = NPN_HTTP1_1;
  589. }
  590. }
  591. #else
  592. (void)sock;
  593. (void)arg;
  594. #endif
  595. }
  596. static void display_cert_info(struct SessionHandle *data,
  597. CERTCertificate *cert)
  598. {
  599. char *subject, *issuer, *common_name;
  600. PRExplodedTime printableTime;
  601. char timeString[256];
  602. PRTime notBefore, notAfter;
  603. subject = CERT_NameToAscii(&cert->subject);
  604. issuer = CERT_NameToAscii(&cert->issuer);
  605. common_name = CERT_GetCommonName(&cert->subject);
  606. infof(data, "\tsubject: %s\n", subject);
  607. CERT_GetCertTimes(cert, &notBefore, &notAfter);
  608. PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
  609. PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
  610. infof(data, "\tstart date: %s\n", timeString);
  611. PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
  612. PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
  613. infof(data, "\texpire date: %s\n", timeString);
  614. infof(data, "\tcommon name: %s\n", common_name);
  615. infof(data, "\tissuer: %s\n", issuer);
  616. PR_Free(subject);
  617. PR_Free(issuer);
  618. PR_Free(common_name);
  619. }
  620. static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
  621. {
  622. CURLcode result = CURLE_OK;
  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. result = Curl_ssl_init_certinfo(conn->data, i);
  663. if(!result) {
  664. for(i = 0; cert; cert = cert2) {
  665. result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
  666. (char *)cert->derCert.data +
  667. cert->derCert.len);
  668. if(result)
  669. break;
  670. if(cert->isRoot) {
  671. CERT_DestroyCertificate(cert);
  672. break;
  673. }
  674. cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
  675. CERT_DestroyCertificate(cert);
  676. }
  677. }
  678. }
  679. }
  680. return result;
  681. }
  682. static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
  683. {
  684. struct connectdata *conn = (struct connectdata *)arg;
  685. struct SessionHandle *data = conn->data;
  686. PRErrorCode err = PR_GetError();
  687. CERTCertificate *cert;
  688. /* remember the cert verification result */
  689. data->set.ssl.certverifyresult = err;
  690. if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
  691. /* we are asked not to verify the host name */
  692. return SECSuccess;
  693. /* print only info about the cert, the error is printed off the callback */
  694. cert = SSL_PeerCertificate(sock);
  695. if(cert) {
  696. infof(data, "Server certificate:\n");
  697. display_cert_info(data, cert);
  698. CERT_DestroyCertificate(cert);
  699. }
  700. return SECFailure;
  701. }
  702. /**
  703. *
  704. * Check that the Peer certificate's issuer certificate matches the one found
  705. * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
  706. * issuer check, so we provide comments that mimic the OpenSSL
  707. * X509_check_issued function (in x509v3/v3_purp.c)
  708. */
  709. static SECStatus check_issuer_cert(PRFileDesc *sock,
  710. char *issuer_nickname)
  711. {
  712. CERTCertificate *cert,*cert_issuer,*issuer;
  713. SECStatus res=SECSuccess;
  714. void *proto_win = NULL;
  715. /*
  716. PRArenaPool *tmpArena = NULL;
  717. CERTAuthKeyID *authorityKeyID = NULL;
  718. SECITEM *caname = NULL;
  719. */
  720. cert = SSL_PeerCertificate(sock);
  721. cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
  722. proto_win = SSL_RevealPinArg(sock);
  723. issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
  724. if((!cert_issuer) || (!issuer))
  725. res = SECFailure;
  726. else if(SECITEM_CompareItem(&cert_issuer->derCert,
  727. &issuer->derCert)!=SECEqual)
  728. res = SECFailure;
  729. CERT_DestroyCertificate(cert);
  730. CERT_DestroyCertificate(issuer);
  731. CERT_DestroyCertificate(cert_issuer);
  732. return res;
  733. }
  734. /**
  735. *
  736. * Callback to pick the SSL client certificate.
  737. */
  738. static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
  739. struct CERTDistNamesStr *caNames,
  740. struct CERTCertificateStr **pRetCert,
  741. struct SECKEYPrivateKeyStr **pRetKey)
  742. {
  743. struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
  744. struct SessionHandle *data = connssl->data;
  745. const char *nickname = connssl->client_nickname;
  746. if(connssl->obj_clicert) {
  747. /* use the cert/key provided by PEM reader */
  748. static const char pem_slotname[] = "PEM Token #1";
  749. SECItem cert_der = { 0, NULL, 0 };
  750. void *proto_win = SSL_RevealPinArg(sock);
  751. struct CERTCertificateStr *cert;
  752. struct SECKEYPrivateKeyStr *key;
  753. PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
  754. if(NULL == slot) {
  755. failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
  756. return SECFailure;
  757. }
  758. if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
  759. &cert_der) != SECSuccess) {
  760. failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
  761. PK11_FreeSlot(slot);
  762. return SECFailure;
  763. }
  764. cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
  765. SECITEM_FreeItem(&cert_der, PR_FALSE);
  766. if(NULL == cert) {
  767. failf(data, "NSS: client certificate from file not found");
  768. PK11_FreeSlot(slot);
  769. return SECFailure;
  770. }
  771. key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
  772. PK11_FreeSlot(slot);
  773. if(NULL == key) {
  774. failf(data, "NSS: private key from file not found");
  775. CERT_DestroyCertificate(cert);
  776. return SECFailure;
  777. }
  778. infof(data, "NSS: client certificate from file\n");
  779. display_cert_info(data, cert);
  780. *pRetCert = cert;
  781. *pRetKey = key;
  782. return SECSuccess;
  783. }
  784. /* use the default NSS hook */
  785. if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
  786. pRetCert, pRetKey)
  787. || NULL == *pRetCert) {
  788. if(NULL == nickname)
  789. failf(data, "NSS: client certificate not found (nickname not "
  790. "specified)");
  791. else
  792. failf(data, "NSS: client certificate not found: %s", nickname);
  793. return SECFailure;
  794. }
  795. /* get certificate nickname if any */
  796. nickname = (*pRetCert)->nickname;
  797. if(NULL == nickname)
  798. nickname = "[unknown]";
  799. if(NULL == *pRetKey) {
  800. failf(data, "NSS: private key not found for certificate: %s", nickname);
  801. return SECFailure;
  802. }
  803. infof(data, "NSS: using client certificate: %s\n", nickname);
  804. display_cert_info(data, *pRetCert);
  805. return SECSuccess;
  806. }
  807. /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
  808. static void nss_update_connecting_state(ssl_connect_state state, void *secret)
  809. {
  810. struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
  811. if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
  812. /* an unrelated error is passing by */
  813. return;
  814. switch(connssl->connecting_state) {
  815. case ssl_connect_2:
  816. case ssl_connect_2_reading:
  817. case ssl_connect_2_writing:
  818. break;
  819. default:
  820. /* we are not called from an SSL handshake */
  821. return;
  822. }
  823. /* update the state accordingly */
  824. connssl->connecting_state = state;
  825. }
  826. /* recv() wrapper we use to detect blocking direction during SSL handshake */
  827. static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
  828. PRIntn flags, PRIntervalTime timeout)
  829. {
  830. const PRRecvFN recv_fn = fd->lower->methods->recv;
  831. const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
  832. if(rv < 0)
  833. /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
  834. nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
  835. return rv;
  836. }
  837. /* send() wrapper we use to detect blocking direction during SSL handshake */
  838. static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
  839. PRIntn flags, PRIntervalTime timeout)
  840. {
  841. const PRSendFN send_fn = fd->lower->methods->send;
  842. const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
  843. if(rv < 0)
  844. /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
  845. nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
  846. return rv;
  847. }
  848. /* close() wrapper to avoid assertion failure due to fd->secret != NULL */
  849. static PRStatus nspr_io_close(PRFileDesc *fd)
  850. {
  851. const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
  852. fd->secret = NULL;
  853. return close_fn(fd);
  854. }
  855. static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir)
  856. {
  857. NSSInitParameters initparams;
  858. if(nss_context != NULL)
  859. return CURLE_OK;
  860. memset((void *) &initparams, '\0', sizeof(initparams));
  861. initparams.length = sizeof(initparams);
  862. if(cert_dir) {
  863. char *certpath = aprintf("sql:%s", cert_dir);
  864. if(!certpath)
  865. return CURLE_OUT_OF_MEMORY;
  866. infof(data, "Initializing NSS with certpath: %s\n", certpath);
  867. nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
  868. NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
  869. free(certpath);
  870. if(nss_context != NULL)
  871. return CURLE_OK;
  872. infof(data, "Unable to initialize NSS database\n");
  873. }
  874. infof(data, "Initializing NSS with certpath: none\n");
  875. nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
  876. | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
  877. | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
  878. if(nss_context != NULL)
  879. return CURLE_OK;
  880. infof(data, "Unable to initialize NSS\n");
  881. return CURLE_SSL_CACERT_BADFILE;
  882. }
  883. static CURLcode nss_init(struct SessionHandle *data)
  884. {
  885. char *cert_dir;
  886. struct_stat st;
  887. CURLcode result;
  888. if(initialized)
  889. return CURLE_OK;
  890. /* list of all CRL items we need to destroy in Curl_nss_cleanup() */
  891. nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
  892. if(!nss_crl_list)
  893. return CURLE_OUT_OF_MEMORY;
  894. /* First we check if $SSL_DIR points to a valid dir */
  895. cert_dir = getenv("SSL_DIR");
  896. if(cert_dir) {
  897. if((stat(cert_dir, &st) != 0) ||
  898. (!S_ISDIR(st.st_mode))) {
  899. cert_dir = NULL;
  900. }
  901. }
  902. /* Now we check if the default location is a valid dir */
  903. if(!cert_dir) {
  904. if((stat(SSL_DIR, &st) == 0) &&
  905. (S_ISDIR(st.st_mode))) {
  906. cert_dir = (char *)SSL_DIR;
  907. }
  908. }
  909. if(nspr_io_identity == PR_INVALID_IO_LAYER) {
  910. /* allocate an identity for our own NSPR I/O layer */
  911. nspr_io_identity = PR_GetUniqueIdentity("libcurl");
  912. if(nspr_io_identity == PR_INVALID_IO_LAYER)
  913. return CURLE_OUT_OF_MEMORY;
  914. /* the default methods just call down to the lower I/O layer */
  915. memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
  916. /* override certain methods in the table by our wrappers */
  917. nspr_io_methods.recv = nspr_io_recv;
  918. nspr_io_methods.send = nspr_io_send;
  919. nspr_io_methods.close = nspr_io_close;
  920. }
  921. result = nss_init_core(data, cert_dir);
  922. if(result)
  923. return result;
  924. if(num_enabled_ciphers() == 0)
  925. NSS_SetDomesticPolicy();
  926. initialized = 1;
  927. return CURLE_OK;
  928. }
  929. /**
  930. * Global SSL init
  931. *
  932. * @retval 0 error initializing SSL
  933. * @retval 1 SSL initialized successfully
  934. */
  935. int Curl_nss_init(void)
  936. {
  937. /* curl_global_init() is not thread-safe so this test is ok */
  938. if(nss_initlock == NULL) {
  939. PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
  940. nss_initlock = PR_NewLock();
  941. nss_crllock = PR_NewLock();
  942. }
  943. /* We will actually initialize NSS later */
  944. return 1;
  945. }
  946. CURLcode Curl_nss_force_init(struct SessionHandle *data)
  947. {
  948. CURLcode result;
  949. if(!nss_initlock) {
  950. failf(data, "unable to initialize NSS, curl_global_init() should have "
  951. "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
  952. return CURLE_FAILED_INIT;
  953. }
  954. PR_Lock(nss_initlock);
  955. result = nss_init(data);
  956. PR_Unlock(nss_initlock);
  957. return result;
  958. }
  959. /* Global cleanup */
  960. void Curl_nss_cleanup(void)
  961. {
  962. /* This function isn't required to be threadsafe and this is only done
  963. * as a safety feature.
  964. */
  965. PR_Lock(nss_initlock);
  966. if(initialized) {
  967. /* Free references to client certificates held in the SSL session cache.
  968. * Omitting this hampers destruction of the security module owning
  969. * the certificates. */
  970. SSL_ClearSessionCache();
  971. if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
  972. SECMOD_DestroyModule(mod);
  973. mod = NULL;
  974. }
  975. NSS_ShutdownContext(nss_context);
  976. nss_context = NULL;
  977. }
  978. /* destroy all CRL items */
  979. Curl_llist_destroy(nss_crl_list, NULL);
  980. nss_crl_list = NULL;
  981. PR_Unlock(nss_initlock);
  982. PR_DestroyLock(nss_initlock);
  983. PR_DestroyLock(nss_crllock);
  984. nss_initlock = NULL;
  985. initialized = 0;
  986. }
  987. /*
  988. * This function uses SSL_peek to determine connection status.
  989. *
  990. * Return codes:
  991. * 1 means the connection is still in place
  992. * 0 means the connection has been closed
  993. * -1 means the connection status is unknown
  994. */
  995. int
  996. Curl_nss_check_cxn(struct connectdata *conn)
  997. {
  998. int rc;
  999. char buf;
  1000. rc =
  1001. PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
  1002. PR_SecondsToInterval(1));
  1003. if(rc > 0)
  1004. return 1; /* connection still in place */
  1005. if(rc == 0)
  1006. return 0; /* connection has been closed */
  1007. return -1; /* connection status unknown */
  1008. }
  1009. /*
  1010. * This function is called when an SSL connection is closed.
  1011. */
  1012. void Curl_nss_close(struct connectdata *conn, int sockindex)
  1013. {
  1014. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1015. if(connssl->handle) {
  1016. /* NSS closes the socket we previously handed to it, so we must mark it
  1017. as closed to avoid double close */
  1018. fake_sclose(conn->sock[sockindex]);
  1019. conn->sock[sockindex] = CURL_SOCKET_BAD;
  1020. if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
  1021. /* A server might require different authentication based on the
  1022. * particular path being requested by the client. To support this
  1023. * scenario, we must ensure that a connection will never reuse the
  1024. * authentication data from a previous connection. */
  1025. SSL_InvalidateSession(connssl->handle);
  1026. if(connssl->client_nickname != NULL) {
  1027. free(connssl->client_nickname);
  1028. connssl->client_nickname = NULL;
  1029. }
  1030. /* destroy all NSS objects in order to avoid failure of NSS shutdown */
  1031. Curl_llist_destroy(connssl->obj_list, NULL);
  1032. connssl->obj_list = NULL;
  1033. connssl->obj_clicert = NULL;
  1034. PR_Close(connssl->handle);
  1035. connssl->handle = NULL;
  1036. }
  1037. }
  1038. /*
  1039. * This function is called when the 'data' struct is going away. Close
  1040. * down everything and free all resources!
  1041. */
  1042. void Curl_nss_close_all(struct SessionHandle *data)
  1043. {
  1044. (void)data;
  1045. }
  1046. /* return true if NSS can provide error code (and possibly msg) for the
  1047. error */
  1048. static bool is_nss_error(CURLcode err)
  1049. {
  1050. switch(err) {
  1051. case CURLE_PEER_FAILED_VERIFICATION:
  1052. case CURLE_SSL_CACERT:
  1053. case CURLE_SSL_CERTPROBLEM:
  1054. case CURLE_SSL_CONNECT_ERROR:
  1055. case CURLE_SSL_ISSUER_ERROR:
  1056. return true;
  1057. default:
  1058. return false;
  1059. }
  1060. }
  1061. /* return true if the given error code is related to a client certificate */
  1062. static bool is_cc_error(PRInt32 err)
  1063. {
  1064. switch(err) {
  1065. case SSL_ERROR_BAD_CERT_ALERT:
  1066. case SSL_ERROR_EXPIRED_CERT_ALERT:
  1067. case SSL_ERROR_REVOKED_CERT_ALERT:
  1068. return true;
  1069. default:
  1070. return false;
  1071. }
  1072. }
  1073. static Curl_recv nss_recv;
  1074. static Curl_send nss_send;
  1075. static CURLcode nss_load_ca_certificates(struct connectdata *conn,
  1076. int sockindex)
  1077. {
  1078. struct SessionHandle *data = conn->data;
  1079. const char *cafile = data->set.ssl.CAfile;
  1080. const char *capath = data->set.ssl.CApath;
  1081. if(cafile) {
  1082. CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
  1083. if(result)
  1084. return result;
  1085. }
  1086. if(capath) {
  1087. struct_stat st;
  1088. if(stat(capath, &st) == -1)
  1089. return CURLE_SSL_CACERT_BADFILE;
  1090. if(S_ISDIR(st.st_mode)) {
  1091. PRDirEntry *entry;
  1092. PRDir *dir = PR_OpenDir(capath);
  1093. if(!dir)
  1094. return CURLE_SSL_CACERT_BADFILE;
  1095. while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
  1096. char *fullpath = aprintf("%s/%s", capath, entry->name);
  1097. if(!fullpath) {
  1098. PR_CloseDir(dir);
  1099. return CURLE_OUT_OF_MEMORY;
  1100. }
  1101. if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
  1102. /* This is purposefully tolerant of errors so non-PEM files can
  1103. * be in the same directory */
  1104. infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
  1105. free(fullpath);
  1106. }
  1107. PR_CloseDir(dir);
  1108. }
  1109. else
  1110. infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
  1111. }
  1112. infof(data, " CAfile: %s\n CApath: %s\n",
  1113. cafile ? cafile : "none",
  1114. capath ? capath : "none");
  1115. return CURLE_OK;
  1116. }
  1117. static CURLcode nss_init_sslver(SSLVersionRange *sslver,
  1118. struct SessionHandle *data)
  1119. {
  1120. switch(data->set.ssl.version) {
  1121. default:
  1122. case CURL_SSLVERSION_DEFAULT:
  1123. case CURL_SSLVERSION_TLSv1:
  1124. sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
  1125. #ifdef SSL_LIBRARY_VERSION_TLS_1_2
  1126. sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
  1127. #elif defined SSL_LIBRARY_VERSION_TLS_1_1
  1128. sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
  1129. #else
  1130. sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
  1131. #endif
  1132. return CURLE_OK;
  1133. case CURL_SSLVERSION_SSLv2:
  1134. sslver->min = SSL_LIBRARY_VERSION_2;
  1135. sslver->max = SSL_LIBRARY_VERSION_2;
  1136. return CURLE_OK;
  1137. case CURL_SSLVERSION_SSLv3:
  1138. sslver->min = SSL_LIBRARY_VERSION_3_0;
  1139. sslver->max = SSL_LIBRARY_VERSION_3_0;
  1140. return CURLE_OK;
  1141. case CURL_SSLVERSION_TLSv1_0:
  1142. sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
  1143. sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
  1144. return CURLE_OK;
  1145. case CURL_SSLVERSION_TLSv1_1:
  1146. #ifdef SSL_LIBRARY_VERSION_TLS_1_1
  1147. sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
  1148. sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
  1149. return CURLE_OK;
  1150. #endif
  1151. break;
  1152. case CURL_SSLVERSION_TLSv1_2:
  1153. #ifdef SSL_LIBRARY_VERSION_TLS_1_2
  1154. sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
  1155. sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
  1156. return CURLE_OK;
  1157. #endif
  1158. break;
  1159. }
  1160. failf(data, "TLS minor version cannot be set");
  1161. return CURLE_SSL_CONNECT_ERROR;
  1162. }
  1163. static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
  1164. struct SessionHandle *data,
  1165. CURLcode curlerr)
  1166. {
  1167. PRErrorCode err = 0;
  1168. if(is_nss_error(curlerr)) {
  1169. /* read NSPR error code */
  1170. err = PR_GetError();
  1171. if(is_cc_error(err))
  1172. curlerr = CURLE_SSL_CERTPROBLEM;
  1173. /* print the error number and error string */
  1174. infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
  1175. /* print a human-readable message describing the error if available */
  1176. nss_print_error_message(data, err);
  1177. }
  1178. /* cleanup on connection failure */
  1179. Curl_llist_destroy(connssl->obj_list, NULL);
  1180. connssl->obj_list = NULL;
  1181. return curlerr;
  1182. }
  1183. /* Switch the SSL socket into non-blocking mode. */
  1184. static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
  1185. struct SessionHandle *data)
  1186. {
  1187. static PRSocketOptionData sock_opt;
  1188. sock_opt.option = PR_SockOpt_Nonblocking;
  1189. sock_opt.value.non_blocking = PR_TRUE;
  1190. if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
  1191. return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
  1192. return CURLE_OK;
  1193. }
  1194. static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
  1195. {
  1196. PRFileDesc *model = NULL;
  1197. PRFileDesc *nspr_io = NULL;
  1198. PRFileDesc *nspr_io_stub = NULL;
  1199. PRBool ssl_no_cache;
  1200. PRBool ssl_cbc_random_iv;
  1201. struct SessionHandle *data = conn->data;
  1202. curl_socket_t sockfd = conn->sock[sockindex];
  1203. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1204. CURLcode result;
  1205. SSLVersionRange sslver = {
  1206. SSL_LIBRARY_VERSION_TLS_1_0, /* min */
  1207. SSL_LIBRARY_VERSION_TLS_1_0 /* max */
  1208. };
  1209. #ifdef USE_NGHTTP2
  1210. #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
  1211. unsigned int alpn_protos_len = NGHTTP2_PROTO_VERSION_ID_LEN +
  1212. ALPN_HTTP_1_1_LENGTH + 2;
  1213. unsigned char alpn_protos[NGHTTP2_PROTO_VERSION_ID_LEN + ALPN_HTTP_1_1_LENGTH
  1214. + 2];
  1215. int cur = 0;
  1216. #endif
  1217. #endif
  1218. connssl->data = data;
  1219. /* list of all NSS objects we need to destroy in Curl_nss_close() */
  1220. connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
  1221. if(!connssl->obj_list)
  1222. return CURLE_OUT_OF_MEMORY;
  1223. /* FIXME. NSS doesn't support multiple databases open at the same time. */
  1224. PR_Lock(nss_initlock);
  1225. result = nss_init(conn->data);
  1226. if(result) {
  1227. PR_Unlock(nss_initlock);
  1228. goto error;
  1229. }
  1230. result = CURLE_SSL_CONNECT_ERROR;
  1231. if(!mod) {
  1232. char *configstring = aprintf("library=%s name=PEM", pem_library);
  1233. if(!configstring) {
  1234. PR_Unlock(nss_initlock);
  1235. goto error;
  1236. }
  1237. mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
  1238. free(configstring);
  1239. if(!mod || !mod->loaded) {
  1240. if(mod) {
  1241. SECMOD_DestroyModule(mod);
  1242. mod = NULL;
  1243. }
  1244. infof(data, "WARNING: failed to load NSS PEM library %s. Using "
  1245. "OpenSSL PEM certificates will not work.\n", pem_library);
  1246. }
  1247. }
  1248. PK11_SetPasswordFunc(nss_get_password);
  1249. PR_Unlock(nss_initlock);
  1250. model = PR_NewTCPSocket();
  1251. if(!model)
  1252. goto error;
  1253. model = SSL_ImportFD(NULL, model);
  1254. if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
  1255. goto error;
  1256. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
  1257. goto error;
  1258. if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
  1259. goto error;
  1260. /* do not use SSL cache if disabled or we are not going to verify peer */
  1261. ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
  1262. PR_FALSE : PR_TRUE;
  1263. if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
  1264. goto error;
  1265. /* enable/disable the requested SSL version(s) */
  1266. if(nss_init_sslver(&sslver, data) != CURLE_OK)
  1267. goto error;
  1268. if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
  1269. goto error;
  1270. ssl_cbc_random_iv = !data->set.ssl_enable_beast;
  1271. #ifdef SSL_CBC_RANDOM_IV
  1272. /* unless the user explicitly asks to allow the protocol vulnerability, we
  1273. use the work-around */
  1274. if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
  1275. infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
  1276. ssl_cbc_random_iv);
  1277. #else
  1278. if(ssl_cbc_random_iv)
  1279. infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
  1280. #endif
  1281. if(data->set.ssl.cipher_list) {
  1282. if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
  1283. result = CURLE_SSL_CIPHER;
  1284. goto error;
  1285. }
  1286. }
  1287. if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
  1288. infof(data, "warning: ignoring value of ssl.verifyhost\n");
  1289. /* bypass the default SSL_AuthCertificate() hook in case we do not want to
  1290. * verify peer */
  1291. if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
  1292. goto error;
  1293. data->set.ssl.certverifyresult=0; /* not checked yet */
  1294. if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
  1295. goto error;
  1296. if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
  1297. goto error;
  1298. if(data->set.ssl.verifypeer) {
  1299. const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
  1300. if(rv) {
  1301. result = rv;
  1302. goto error;
  1303. }
  1304. }
  1305. if(data->set.ssl.CRLfile) {
  1306. const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
  1307. if(rv) {
  1308. result = rv;
  1309. goto error;
  1310. }
  1311. infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
  1312. }
  1313. if(data->set.str[STRING_CERT]) {
  1314. char *nickname = dup_nickname(data, STRING_CERT);
  1315. if(nickname) {
  1316. /* we are not going to use libnsspem.so to read the client cert */
  1317. connssl->obj_clicert = NULL;
  1318. }
  1319. else {
  1320. CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
  1321. data->set.str[STRING_KEY]);
  1322. if(rv) {
  1323. /* failf() is already done in cert_stuff() */
  1324. result = rv;
  1325. goto error;
  1326. }
  1327. }
  1328. /* store the nickname for SelectClientCert() called during handshake */
  1329. connssl->client_nickname = nickname;
  1330. }
  1331. else
  1332. connssl->client_nickname = NULL;
  1333. if(SSL_GetClientAuthDataHook(model, SelectClientCert,
  1334. (void *)connssl) != SECSuccess) {
  1335. result = CURLE_SSL_CERTPROBLEM;
  1336. goto error;
  1337. }
  1338. /* wrap OS file descriptor by NSPR's file descriptor abstraction */
  1339. nspr_io = PR_ImportTCPSocket(sockfd);
  1340. if(!nspr_io)
  1341. goto error;
  1342. /* create our own NSPR I/O layer */
  1343. nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
  1344. if(!nspr_io_stub) {
  1345. PR_Close(nspr_io);
  1346. goto error;
  1347. }
  1348. /* make the per-connection data accessible from NSPR I/O callbacks */
  1349. nspr_io_stub->secret = (void *)connssl;
  1350. /* push our new layer to the NSPR I/O stack */
  1351. if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
  1352. PR_Close(nspr_io);
  1353. PR_Close(nspr_io_stub);
  1354. goto error;
  1355. }
  1356. /* import our model socket onto the current I/O stack */
  1357. connssl->handle = SSL_ImportFD(model, nspr_io);
  1358. if(!connssl->handle) {
  1359. PR_Close(nspr_io);
  1360. goto error;
  1361. }
  1362. PR_Close(model); /* We don't need this any more */
  1363. model = NULL;
  1364. /* This is the password associated with the cert that we're using */
  1365. if(data->set.str[STRING_KEY_PASSWD]) {
  1366. SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
  1367. }
  1368. #ifdef USE_NGHTTP2
  1369. if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
  1370. #ifdef SSL_ENABLE_NPN
  1371. if(data->set.ssl_enable_npn) {
  1372. if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, PR_TRUE) != SECSuccess)
  1373. goto error;
  1374. }
  1375. #endif
  1376. #ifdef SSL_ENABLE_ALPN
  1377. if(data->set.ssl_enable_alpn) {
  1378. if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, PR_TRUE)
  1379. != SECSuccess)
  1380. goto error;
  1381. }
  1382. #endif
  1383. #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
  1384. if(data->set.ssl_enable_npn || data->set.ssl_enable_alpn) {
  1385. alpn_protos[cur] = NGHTTP2_PROTO_VERSION_ID_LEN;
  1386. cur++;
  1387. memcpy(&alpn_protos[cur], NGHTTP2_PROTO_VERSION_ID,
  1388. NGHTTP2_PROTO_VERSION_ID_LEN);
  1389. cur += NGHTTP2_PROTO_VERSION_ID_LEN;
  1390. alpn_protos[cur] = ALPN_HTTP_1_1_LENGTH;
  1391. cur++;
  1392. memcpy(&alpn_protos[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
  1393. if(SSL_SetNextProtoNego(connssl->handle, alpn_protos, alpn_protos_len)
  1394. != SECSuccess)
  1395. goto error;
  1396. connssl->asked_for_h2 = TRUE;
  1397. }
  1398. else {
  1399. infof(data, "SSL, can't negotiate HTTP/2.0 with neither NPN nor ALPN\n");
  1400. }
  1401. #endif
  1402. }
  1403. #endif
  1404. /* Force handshake on next I/O */
  1405. SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
  1406. SSL_SetURL(connssl->handle, conn->host.name);
  1407. return CURLE_OK;
  1408. error:
  1409. if(model)
  1410. PR_Close(model);
  1411. return nss_fail_connect(connssl, data, result);
  1412. }
  1413. static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
  1414. {
  1415. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1416. struct SessionHandle *data = conn->data;
  1417. CURLcode result = CURLE_SSL_CONNECT_ERROR;
  1418. PRUint32 timeout;
  1419. /* check timeout situation */
  1420. const long time_left = Curl_timeleft(data, NULL, TRUE);
  1421. if(time_left < 0L) {
  1422. failf(data, "timed out before SSL handshake");
  1423. result = CURLE_OPERATION_TIMEDOUT;
  1424. goto error;
  1425. }
  1426. /* Force the handshake now */
  1427. timeout = PR_MillisecondsToInterval((PRUint32) time_left);
  1428. if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
  1429. if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
  1430. /* blocking direction is updated by nss_update_connecting_state() */
  1431. return CURLE_AGAIN;
  1432. else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
  1433. result = CURLE_PEER_FAILED_VERIFICATION;
  1434. else if(conn->data->set.ssl.certverifyresult!=0)
  1435. result = CURLE_SSL_CACERT;
  1436. goto error;
  1437. }
  1438. result = display_conn_info(conn, connssl->handle);
  1439. if(result)
  1440. goto error;
  1441. if(data->set.str[STRING_SSL_ISSUERCERT]) {
  1442. SECStatus ret = SECFailure;
  1443. char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
  1444. if(nickname) {
  1445. /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
  1446. ret = check_issuer_cert(connssl->handle, nickname);
  1447. free(nickname);
  1448. }
  1449. if(SECFailure == ret) {
  1450. infof(data,"SSL certificate issuer check failed\n");
  1451. result = CURLE_SSL_ISSUER_ERROR;
  1452. goto error;
  1453. }
  1454. else {
  1455. infof(data, "SSL certificate issuer check ok\n");
  1456. }
  1457. }
  1458. return CURLE_OK;
  1459. error:
  1460. return nss_fail_connect(connssl, data, result);
  1461. }
  1462. static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
  1463. bool *done)
  1464. {
  1465. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1466. struct SessionHandle *data = conn->data;
  1467. const bool blocking = (done == NULL);
  1468. CURLcode result;
  1469. if(connssl->state == ssl_connection_complete)
  1470. return CURLE_OK;
  1471. if(connssl->connecting_state == ssl_connect_1) {
  1472. result = nss_setup_connect(conn, sockindex);
  1473. if(result)
  1474. /* we do not expect CURLE_AGAIN from nss_setup_connect() */
  1475. return result;
  1476. if(!blocking) {
  1477. /* in non-blocking mode, set NSS non-blocking mode before handshake */
  1478. result = nss_set_nonblock(connssl, data);
  1479. if(result)
  1480. return result;
  1481. }
  1482. connssl->connecting_state = ssl_connect_2;
  1483. }
  1484. result = nss_do_connect(conn, sockindex);
  1485. switch(result) {
  1486. case CURLE_OK:
  1487. break;
  1488. case CURLE_AGAIN:
  1489. if(!blocking)
  1490. /* CURLE_AGAIN in non-blocking mode is not an error */
  1491. return CURLE_OK;
  1492. /* fall through */
  1493. default:
  1494. return result;
  1495. }
  1496. if(blocking) {
  1497. /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
  1498. result = nss_set_nonblock(connssl, data);
  1499. if(result)
  1500. return result;
  1501. }
  1502. else
  1503. /* signal completed SSL handshake */
  1504. *done = TRUE;
  1505. connssl->state = ssl_connection_complete;
  1506. conn->recv[sockindex] = nss_recv;
  1507. conn->send[sockindex] = nss_send;
  1508. /* ssl_connect_done is never used outside, go back to the initial state */
  1509. connssl->connecting_state = ssl_connect_1;
  1510. return CURLE_OK;
  1511. }
  1512. CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
  1513. {
  1514. return nss_connect_common(conn, sockindex, /* blocking */ NULL);
  1515. }
  1516. CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
  1517. int sockindex, bool *done)
  1518. {
  1519. return nss_connect_common(conn, sockindex, done);
  1520. }
  1521. static ssize_t nss_send(struct connectdata *conn, /* connection data */
  1522. int sockindex, /* socketindex */
  1523. const void *mem, /* send this data */
  1524. size_t len, /* amount to write */
  1525. CURLcode *curlcode)
  1526. {
  1527. ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
  1528. PR_INTERVAL_NO_WAIT);
  1529. if(rc < 0) {
  1530. PRInt32 err = PR_GetError();
  1531. if(err == PR_WOULD_BLOCK_ERROR)
  1532. *curlcode = CURLE_AGAIN;
  1533. else {
  1534. /* print the error number and error string */
  1535. const char *err_name = nss_error_to_name(err);
  1536. infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
  1537. /* print a human-readable message describing the error if available */
  1538. nss_print_error_message(conn->data, err);
  1539. *curlcode = (is_cc_error(err))
  1540. ? CURLE_SSL_CERTPROBLEM
  1541. : CURLE_SEND_ERROR;
  1542. }
  1543. return -1;
  1544. }
  1545. return rc; /* number of bytes */
  1546. }
  1547. static ssize_t nss_recv(struct connectdata * conn, /* connection data */
  1548. int num, /* socketindex */
  1549. char *buf, /* store read data here */
  1550. size_t buffersize, /* max amount to read */
  1551. CURLcode *curlcode)
  1552. {
  1553. ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
  1554. PR_INTERVAL_NO_WAIT);
  1555. if(nread < 0) {
  1556. /* failed SSL read */
  1557. PRInt32 err = PR_GetError();
  1558. if(err == PR_WOULD_BLOCK_ERROR)
  1559. *curlcode = CURLE_AGAIN;
  1560. else {
  1561. /* print the error number and error string */
  1562. const char *err_name = nss_error_to_name(err);
  1563. infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
  1564. /* print a human-readable message describing the error if available */
  1565. nss_print_error_message(conn->data, err);
  1566. *curlcode = (is_cc_error(err))
  1567. ? CURLE_SSL_CERTPROBLEM
  1568. : CURLE_RECV_ERROR;
  1569. }
  1570. return -1;
  1571. }
  1572. return nread;
  1573. }
  1574. size_t Curl_nss_version(char *buffer, size_t size)
  1575. {
  1576. return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
  1577. }
  1578. int Curl_nss_seed(struct SessionHandle *data)
  1579. {
  1580. /* make sure that NSS is initialized */
  1581. return !!Curl_nss_force_init(data);
  1582. }
  1583. /* data might be NULL */
  1584. int Curl_nss_random(struct SessionHandle *data,
  1585. unsigned char *entropy,
  1586. size_t length)
  1587. {
  1588. if(data)
  1589. Curl_nss_seed(data); /* Initiate the seed if not already done */
  1590. if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length))) {
  1591. /* no way to signal a failure from here, we have to abort */
  1592. failf(data, "PK11_GenerateRandom() failed, calling abort()...");
  1593. abort();
  1594. }
  1595. return 0;
  1596. }
  1597. void Curl_nss_md5sum(unsigned char *tmp, /* input */
  1598. size_t tmplen,
  1599. unsigned char *md5sum, /* output */
  1600. size_t md5len)
  1601. {
  1602. PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
  1603. unsigned int MD5out;
  1604. PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
  1605. PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
  1606. PK11_DestroyContext(MD5pw, PR_TRUE);
  1607. }
  1608. #endif /* USE_NSS */