nss.c 60 KB

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