AsyncSslSocketLayer.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. // CAsyncSslSocketLayer by Tim Kosse ([email protected])
  2. // Version 2.0 (2005-02-27)
  3. //---------------------------------------------------------------------------
  4. // Feel free to use this class, as long as you don't claim that you wrote it
  5. // and this copyright notice stays intact in the source files.
  6. // If you use this class in commercial applications, please send a short message
  7. // to [email protected]
  8. //---------------------------------------------------------------------------
  9. #include "stdafx.h"
  10. #include "AsyncSslSocketLayer.h"
  11. #include <openssl/x509v3.h>
  12. #include <openssl/err.h>
  13. /////////////////////////////////////////////////////////////////////////////
  14. // CAsyncSslSocketLayer
  15. CCriticalSectionWrapper CAsyncSslSocketLayer::m_sCriticalSection;
  16. CAsyncSslSocketLayer::t_SslLayerList* CAsyncSslSocketLayer::m_pSslLayerList = 0;
  17. int CAsyncSslSocketLayer::m_nSslRefCount = 0;
  18. std::map<SSL_CTX *, int> CAsyncSslSocketLayer::m_contextRefCount;
  19. CAsyncSslSocketLayer::CAsyncSslSocketLayer()
  20. {
  21. m_ssl = 0;
  22. m_sslbio = 0;
  23. m_ibio = 0;
  24. m_nbio = 0;
  25. m_ssl_ctx = 0;
  26. m_bUseSSL = false;
  27. m_bSslInitialized = FALSE;
  28. m_bSslEstablished = FALSE;
  29. m_nNetworkSendBufferLen = 0;
  30. m_nNetworkSendBufferMaxLen = 0;
  31. m_pNetworkSendBuffer = NULL;
  32. m_pRetrySendBuffer = 0;
  33. m_nRetrySendBufferLen = 0;
  34. m_nNetworkError = 0;
  35. m_nShutDown = 0;
  36. m_bBlocking = FALSE;
  37. m_nSslAsyncNotifyId = 0;
  38. m_bFailureSent = FALSE;
  39. m_nVerificationResult = 0;
  40. m_nVerificationDepth = 0;
  41. m_mayTriggerRead = true;
  42. m_mayTriggerWrite = true;
  43. m_mayTriggerReadUp = true;
  44. m_mayTriggerWriteUp = true;
  45. m_onCloseCalled = false;
  46. m_Main = NULL;
  47. m_sessionid = NULL;
  48. m_sessionreuse = true;
  49. FCertificate = NULL;
  50. FPrivateKey = NULL;
  51. }
  52. CAsyncSslSocketLayer::~CAsyncSslSocketLayer()
  53. {
  54. UnloadSSL();
  55. delete [] m_pNetworkSendBuffer;
  56. delete [] m_pRetrySendBuffer;
  57. }
  58. int CAsyncSslSocketLayer::InitSSL()
  59. {
  60. if (m_bSslInitialized)
  61. return 0;
  62. m_sCriticalSection.Lock();
  63. if (!m_nSslRefCount)
  64. {
  65. SSL_load_error_strings();
  66. if (!SSL_library_init())
  67. {
  68. return SSL_FAILURE_INITSSL;
  69. }
  70. }
  71. m_nSslRefCount++;
  72. m_sCriticalSection.Unlock();
  73. m_bSslInitialized = true;
  74. return 0;
  75. }
  76. void CAsyncSslSocketLayer::OnReceive(int nErrorCode)
  77. {
  78. if (m_bUseSSL)
  79. {
  80. if (m_bBlocking)
  81. {
  82. m_mayTriggerRead = true;
  83. return;
  84. }
  85. if (m_nNetworkError)
  86. {
  87. return;
  88. }
  89. char buffer[16384];
  90. m_mayTriggerRead = false;
  91. //Get number of bytes we can receive and store in the network input bio
  92. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  93. if (len > 16384)
  94. len = 16384;
  95. else if (!len)
  96. {
  97. m_mayTriggerRead = true;
  98. TriggerEvents();
  99. return;
  100. }
  101. int numread = 0;
  102. // Receive data
  103. numread = ReceiveNext(buffer, len);
  104. if (numread > 0)
  105. {
  106. //Store it in the network input bio and process data
  107. int numwritten = BIO_write(m_nbio, buffer, numread);
  108. BIO_ctrl(m_nbio, BIO_CTRL_FLUSH, 0, NULL);
  109. // I have no idea why this call is needed, but without it, connections
  110. // will stall. Perhaps it triggers some internal processing.
  111. // Also, ignore return value, don't do any error checking. This function
  112. // can report errors, even though a later call can succeed.
  113. char buffer;
  114. BIO_read(m_sslbio, &buffer, 0);
  115. }
  116. if (!numread)
  117. {
  118. if (GetLayerState() == connected)
  119. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  120. }
  121. else if (numread == SOCKET_ERROR)
  122. {
  123. int nError = GetLastError();
  124. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  125. {
  126. m_nNetworkError = GetLastError();
  127. TriggerEvent(FD_CLOSE, 0, TRUE);
  128. return;
  129. }
  130. }
  131. if (m_pRetrySendBuffer)
  132. {
  133. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  134. if (numwrite >= 0)
  135. {
  136. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  137. delete [] m_pRetrySendBuffer;
  138. m_pRetrySendBuffer = 0;
  139. }
  140. else if (numwrite == -1)
  141. {
  142. if (!BIO_should_retry(m_sslbio))
  143. {
  144. delete [] m_pRetrySendBuffer;
  145. m_pRetrySendBuffer = 0;
  146. ::SetLastError(WSAECONNABORTED);
  147. TriggerEvent(FD_CLOSE, 0, TRUE);
  148. return;
  149. }
  150. }
  151. }
  152. if (!m_nShutDown && SSL_get_shutdown(m_ssl))
  153. {
  154. size_t pending = BIO_ctrl_pending(m_sslbio);
  155. if (pending <= 0)
  156. {
  157. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  158. {
  159. if (ShutDownComplete())
  160. TriggerEvent(FD_CLOSE, 0, TRUE);
  161. }
  162. else
  163. {
  164. m_nNetworkError = WSAECONNABORTED;
  165. WSASetLastError(WSAECONNABORTED);
  166. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  167. }
  168. return;
  169. }
  170. }
  171. if (ShutDownComplete() && m_nShutDown == 1)
  172. {
  173. //Send shutdown notification if all pending data has been sent
  174. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  175. m_nShutDown++;
  176. }
  177. TriggerEvents();
  178. }
  179. else
  180. {
  181. TriggerEvent(FD_READ, nErrorCode, TRUE);
  182. }
  183. }
  184. void CAsyncSslSocketLayer::OnSend(int nErrorCode)
  185. {
  186. if (m_bUseSSL)
  187. {
  188. if (m_nNetworkError)
  189. {
  190. return;
  191. }
  192. m_mayTriggerWrite = false;
  193. //Send data in the send buffer
  194. while (m_nNetworkSendBufferLen)
  195. {
  196. int numsent = SendNext(m_pNetworkSendBuffer, m_nNetworkSendBufferLen);
  197. if (numsent == SOCKET_ERROR)
  198. {
  199. int nError = GetLastError();
  200. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  201. {
  202. m_nNetworkError = nError;
  203. TriggerEvent(FD_CLOSE, 0, TRUE);
  204. }
  205. return;
  206. }
  207. else if (!numsent)
  208. {
  209. if (GetLayerState() == connected)
  210. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  211. }
  212. if (numsent == m_nNetworkSendBufferLen)
  213. {
  214. m_nNetworkSendBufferLen = 0;
  215. }
  216. else
  217. {
  218. memmove(m_pNetworkSendBuffer, m_pNetworkSendBuffer + numsent, m_nNetworkSendBufferLen - numsent);
  219. m_nNetworkSendBufferLen -= numsent;
  220. }
  221. }
  222. //Send the data waiting in the network bio
  223. char buffer[32 * 1024];
  224. size_t len = BIO_ctrl_pending(m_nbio);
  225. int numread = BIO_read(m_nbio, buffer, std::min(len, sizeof(buffer)));
  226. if (numread <= 0)
  227. m_mayTriggerWrite = true;
  228. while (numread > 0)
  229. {
  230. int numsent = SendNext(buffer, numread);
  231. if (!numsent)
  232. {
  233. if (GetLayerState() == connected)
  234. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  235. }
  236. if (numsent == SOCKET_ERROR || numsent < numread)
  237. {
  238. if (numsent == SOCKET_ERROR)
  239. if (GetLastError() != WSAEWOULDBLOCK && GetLastError() != WSAENOTCONN)
  240. {
  241. m_nNetworkError = GetLastError();
  242. TriggerEvent(FD_CLOSE, 0, TRUE);
  243. return;
  244. }
  245. else
  246. numsent = 0;
  247. // Add all data that was retrieved from the network bio but could not be sent to the send buffer.
  248. if (m_nNetworkSendBufferMaxLen < (m_nNetworkSendBufferLen + numread - numsent))
  249. {
  250. char * tmp = m_pNetworkSendBuffer;
  251. m_nNetworkSendBufferMaxLen = static_cast<int>((m_nNetworkSendBufferLen + numread - numsent) * 1.5);
  252. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  253. if (tmp)
  254. {
  255. memcpy(m_pNetworkSendBuffer, tmp, m_nNetworkSendBufferLen);
  256. delete [] tmp;
  257. }
  258. }
  259. DebugAssert(m_pNetworkSendBuffer);
  260. memcpy(m_pNetworkSendBuffer + m_nNetworkSendBufferLen, buffer, numread-numsent);
  261. m_nNetworkSendBufferLen += numread - numsent;
  262. }
  263. if (!numsent)
  264. {
  265. break;
  266. }
  267. len = BIO_ctrl_pending(m_nbio);
  268. if (!len)
  269. {
  270. m_mayTriggerWrite = true;
  271. break;
  272. }
  273. numread = BIO_read(m_nbio, buffer, len);
  274. if (numread <= 0)
  275. {
  276. m_mayTriggerWrite = true;
  277. }
  278. }
  279. if (m_pRetrySendBuffer)
  280. {
  281. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  282. if (numwrite >= 0)
  283. {
  284. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  285. delete [] m_pRetrySendBuffer;
  286. m_pRetrySendBuffer = 0;
  287. }
  288. else if (numwrite == -1)
  289. {
  290. if (!BIO_should_retry(m_sslbio))
  291. {
  292. delete [] m_pRetrySendBuffer;
  293. m_pRetrySendBuffer = 0;
  294. ::SetLastError(WSAECONNABORTED);
  295. TriggerEvent(FD_CLOSE, 0, TRUE);
  296. return;
  297. }
  298. }
  299. }
  300. // No more data available, ask for more.
  301. TriggerEvents();
  302. if (m_nShutDown == 1 && ShutDownComplete())
  303. {
  304. //Send shutdown notification if all pending data has been sent
  305. // FileZilla3 calls ShutDownNext() here
  306. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  307. m_nShutDown++;
  308. }
  309. }
  310. else
  311. {
  312. TriggerEvent(FD_WRITE, nErrorCode, TRUE);
  313. }
  314. }
  315. int CAsyncSslSocketLayer::Send(const void* lpBuf, int nBufLen, int nFlags)
  316. {
  317. if (m_bUseSSL)
  318. {
  319. if (!lpBuf)
  320. {
  321. return 0;
  322. }
  323. if (m_bBlocking || m_pRetrySendBuffer)
  324. {
  325. m_mayTriggerWriteUp = true;
  326. ::SetLastError(WSAEWOULDBLOCK);
  327. return SOCKET_ERROR;
  328. }
  329. if (m_nNetworkError)
  330. {
  331. SetLastError(m_nNetworkError);
  332. return SOCKET_ERROR;
  333. }
  334. if (m_nShutDown)
  335. {
  336. ::SetLastError(WSAESHUTDOWN);
  337. return SOCKET_ERROR;
  338. }
  339. if (!m_bSslEstablished)
  340. {
  341. m_mayTriggerWriteUp = true;
  342. ::SetLastError(WSAEWOULDBLOCK);
  343. return SOCKET_ERROR;
  344. }
  345. if (!nBufLen)
  346. {
  347. return 0;
  348. }
  349. if (m_onCloseCalled)
  350. {
  351. TriggerEvent(FD_CLOSE, 0, TRUE);
  352. return 0;
  353. }
  354. int len = BIO_ctrl_get_write_guarantee(m_sslbio);
  355. if (nBufLen > len)
  356. nBufLen = len;
  357. if (!len)
  358. {
  359. m_mayTriggerWriteUp = true;
  360. TriggerEvents();
  361. ::SetLastError(WSAEWOULDBLOCK);
  362. }
  363. m_pRetrySendBuffer = new char[nBufLen];
  364. m_nRetrySendBufferLen = nBufLen;
  365. memcpy(m_pRetrySendBuffer, lpBuf, nBufLen);
  366. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  367. if (numwrite >= 0)
  368. {
  369. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  370. delete [] m_pRetrySendBuffer;
  371. m_pRetrySendBuffer = 0;
  372. }
  373. else if (numwrite == -1)
  374. {
  375. if (BIO_should_retry(m_sslbio))
  376. {
  377. if (GetLayerState() == closed)
  378. {
  379. return 0;
  380. }
  381. else if (GetLayerState() != connected)
  382. {
  383. SetLastError(m_nNetworkError);
  384. return SOCKET_ERROR;
  385. }
  386. TriggerEvents();
  387. return nBufLen;
  388. }
  389. else
  390. {
  391. delete [] m_pRetrySendBuffer;
  392. m_pRetrySendBuffer = 0;
  393. ::SetLastError(WSAECONNABORTED);
  394. }
  395. return SOCKET_ERROR;
  396. }
  397. m_mayTriggerWriteUp = true;
  398. TriggerEvents();
  399. return numwrite;
  400. }
  401. else
  402. {
  403. return SendNext(lpBuf, nBufLen, nFlags);
  404. }
  405. }
  406. int CAsyncSslSocketLayer::Receive(void* lpBuf, int nBufLen, int nFlags)
  407. {
  408. if (m_bUseSSL)
  409. {
  410. if (m_bBlocking)
  411. {
  412. m_mayTriggerReadUp = true;
  413. ::SetLastError(WSAEWOULDBLOCK);
  414. return SOCKET_ERROR;
  415. }
  416. if (m_nNetworkError)
  417. {
  418. size_t pending = BIO_ctrl_pending(m_sslbio);
  419. if (pending && !m_nShutDown)
  420. {
  421. m_mayTriggerReadUp = true;
  422. TriggerEvents();
  423. return BIO_read(m_sslbio, lpBuf,nBufLen);
  424. }
  425. WSASetLastError(m_nNetworkError);
  426. return SOCKET_ERROR;
  427. }
  428. if (m_nShutDown)
  429. {
  430. ::SetLastError(WSAESHUTDOWN);
  431. return SOCKET_ERROR;
  432. }
  433. if (!nBufLen)
  434. {
  435. return 0;
  436. }
  437. size_t pending = BIO_ctrl_pending(m_sslbio);
  438. if (!pending)
  439. {
  440. if (GetLayerState() == closed)
  441. {
  442. return 0;
  443. }
  444. if (m_onCloseCalled)
  445. {
  446. TriggerEvent(FD_CLOSE, 0, TRUE);
  447. return 0;
  448. }
  449. else if (GetLayerState() != connected)
  450. {
  451. SetLastError(m_nNetworkError);
  452. return SOCKET_ERROR;
  453. }
  454. else
  455. {
  456. if (SSL_get_shutdown(m_ssl))
  457. {
  458. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  459. {
  460. if (ShutDownComplete())
  461. {
  462. TriggerEvent(FD_CLOSE, 0, TRUE);
  463. return 0;
  464. }
  465. else
  466. WSASetLastError(WSAEWOULDBLOCK);
  467. }
  468. else
  469. {
  470. m_nNetworkError = WSAECONNABORTED;
  471. WSASetLastError(WSAECONNABORTED);
  472. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  473. }
  474. return SOCKET_ERROR;
  475. }
  476. }
  477. m_mayTriggerReadUp = true;
  478. TriggerEvents();
  479. ::SetLastError(WSAEWOULDBLOCK);
  480. return SOCKET_ERROR;
  481. }
  482. int numread = BIO_read(m_sslbio, lpBuf, nBufLen);
  483. if (!numread)
  484. {
  485. if (SSL_get_shutdown(m_ssl))
  486. {
  487. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  488. {
  489. if (ShutDownComplete())
  490. {
  491. TriggerEvent(FD_CLOSE, 0, TRUE);
  492. return 0;
  493. }
  494. else
  495. WSASetLastError(WSAEWOULDBLOCK);
  496. }
  497. else
  498. {
  499. m_nNetworkError = WSAECONNABORTED;
  500. WSASetLastError(WSAECONNABORTED);
  501. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  502. }
  503. return SOCKET_ERROR;
  504. }
  505. m_mayTriggerReadUp = true;
  506. TriggerEvents();
  507. ::SetLastError(WSAEWOULDBLOCK);
  508. return SOCKET_ERROR;
  509. }
  510. if (numread < 0)
  511. {
  512. if (!BIO_should_retry(m_sslbio))
  513. {
  514. PrintLastErrorMsg();
  515. m_nNetworkError = WSAECONNABORTED;
  516. WSASetLastError(WSAECONNABORTED);
  517. TriggerEvent(FD_CLOSE, 0, TRUE);
  518. return SOCKET_ERROR;
  519. }
  520. else
  521. {
  522. if (SSL_get_shutdown(m_ssl))
  523. {
  524. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  525. {
  526. if (ShutDownComplete())
  527. {
  528. TriggerEvent(FD_CLOSE, 0, TRUE);
  529. return 0;
  530. }
  531. else
  532. WSASetLastError(WSAEWOULDBLOCK);
  533. }
  534. else
  535. {
  536. m_nNetworkError = WSAECONNABORTED;
  537. WSASetLastError(WSAECONNABORTED);
  538. TriggerEvent(FD_CLOSE, 0, TRUE);
  539. }
  540. return SOCKET_ERROR;
  541. }
  542. m_mayTriggerReadUp = true;
  543. TriggerEvents();
  544. ::SetLastError(WSAEWOULDBLOCK);
  545. return SOCKET_ERROR;
  546. }
  547. }
  548. m_mayTriggerReadUp = true;
  549. TriggerEvents();
  550. return numread;
  551. }
  552. else
  553. {
  554. return ReceiveNext(lpBuf, nBufLen, nFlags);
  555. }
  556. }
  557. void CAsyncSslSocketLayer::Close()
  558. {
  559. m_nShutDown = 0;
  560. m_onCloseCalled = false;
  561. ResetSslSession();
  562. CloseNext();
  563. }
  564. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  565. {
  566. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  567. if (!res)
  568. {
  569. if (GetLastError() != WSAEWOULDBLOCK)
  570. {
  571. ResetSslSession();
  572. }
  573. }
  574. return res;
  575. }
  576. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  577. {
  578. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  579. if (!res)
  580. {
  581. if (GetLastError()!=WSAEWOULDBLOCK)
  582. {
  583. ResetSslSession();
  584. }
  585. }
  586. return res;
  587. }
  588. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  589. CAsyncSslSocketLayer* main, bool sessionreuse,
  590. int minTlsVersion, int maxTlsVersion,
  591. void* pSslContext /*=0*/)
  592. {
  593. if (m_bUseSSL)
  594. return 0;
  595. int res = InitSSL();
  596. if (res)
  597. return res;
  598. m_sCriticalSection.Lock();
  599. if ((SSL_CTX*)pSslContext)
  600. {
  601. if (m_ssl_ctx)
  602. {
  603. m_sCriticalSection.Unlock();
  604. ResetSslSession();
  605. return SSL_FAILURE_INITSSL;
  606. }
  607. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  608. if (iter == m_contextRefCount.end() || iter->second < 1)
  609. {
  610. m_sCriticalSection.Unlock();
  611. ResetSslSession();
  612. return SSL_FAILURE_INITSSL;
  613. }
  614. m_ssl_ctx = (SSL_CTX*)pSslContext;
  615. iter->second++;
  616. }
  617. else if (!m_ssl_ctx)
  618. {
  619. // Create new context if none given
  620. if (!(m_ssl_ctx = SSL_CTX_new( SSLv23_method())))
  621. {
  622. m_sCriticalSection.Unlock();
  623. ResetSslSession();
  624. return SSL_FAILURE_INITSSL;
  625. }
  626. m_contextRefCount[m_ssl_ctx] = 1;
  627. if (clientMode)
  628. {
  629. USES_CONVERSION;
  630. SSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  631. SSL_CTX_set_client_cert_cb(m_ssl_ctx, ProvideClientCert);
  632. CFileStatus Dummy;
  633. if (CFile::GetStatus((LPCTSTR)m_CertStorage, Dummy))
  634. {
  635. SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  636. }
  637. }
  638. }
  639. //Create new SSL session
  640. if (!(m_ssl = SSL_new(m_ssl_ctx)))
  641. {
  642. m_sCriticalSection.Unlock();
  643. ResetSslSession();
  644. return SSL_FAILURE_INITSSL;
  645. }
  646. #ifdef _DEBUG
  647. if ((main == NULL) && LoggingSocketMessage(FZ_LOG_INFO))
  648. {
  649. USES_CONVERSION;
  650. LogSocketMessageRaw(FZ_LOG_INFO, L"Supported ciphersuites:");
  651. STACK_OF(SSL_CIPHER) * ciphers = SSL_get_ciphers(m_ssl);
  652. for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); i++)
  653. {
  654. SSL_CIPHER * cipher = sk_SSL_CIPHER_value(ciphers, i);
  655. LogSocketMessageRaw(FZ_LOG_INFO, A2CT(cipher->name));
  656. }
  657. }
  658. #endif
  659. //Add current instance to list of active instances
  660. t_SslLayerList *tmp = m_pSslLayerList;
  661. m_pSslLayerList = new t_SslLayerList;
  662. m_pSslLayerList->pNext = tmp;
  663. m_pSslLayerList->pLayer = this;
  664. m_sCriticalSection.Unlock();
  665. SSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  666. //Create bios
  667. m_sslbio = BIO_new(BIO_f_ssl());
  668. BIO_new_bio_pair(&m_ibio, 32768, &m_nbio, 32768);
  669. if (!m_sslbio || !m_nbio || !m_ibio)
  670. {
  671. ResetSslSession();
  672. return SSL_FAILURE_INITSSL;
  673. }
  674. // See also TWebDAVFileSystem::InitSslSession
  675. #define MASK_TLS_VERSION(VERSION, FLAG) ((minTlsVersion > VERSION) || (maxTlsVersion < VERSION) ? FLAG : 0)
  676. long options =
  677. SSL_OP_ALL |
  678. MASK_TLS_VERSION(SSL_VERSION_SSL2, SSL_OP_NO_SSLv2) |
  679. MASK_TLS_VERSION(SSL_VERSION_SSL3, SSL_OP_NO_SSLv3) |
  680. MASK_TLS_VERSION(SSL_VERSION_TLS10, SSL_OP_NO_TLSv1) |
  681. MASK_TLS_VERSION(SSL_VERSION_TLS11, SSL_OP_NO_TLSv1_1) |
  682. MASK_TLS_VERSION(SSL_VERSION_TLS12, SSL_OP_NO_TLSv1_2);
  683. // SSL_ctrl() with SSL_CTRL_OPTIONS adds flags (not sets)
  684. SSL_ctrl(m_ssl, SSL_CTRL_OPTIONS, options, NULL);
  685. //Init SSL connection
  686. void *ssl_sessionid = NULL;
  687. m_Main = main;
  688. m_sessionreuse = sessionreuse;
  689. if ((m_Main != NULL) && m_sessionreuse)
  690. {
  691. if (m_Main->m_sessionid != NULL)
  692. {
  693. if (!SSL_set_session(m_ssl, m_Main->m_sessionid))
  694. {
  695. LogSocketMessageRaw(FZ_LOG_INFO, L"SSL_set_session failed");
  696. return SSL_FAILURE_INITSSL;
  697. }
  698. LogSocketMessageRaw(FZ_LOG_INFO, L"Trying reuse main TLS session ID");
  699. }
  700. else
  701. {
  702. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID was not reused previously, not trying again");
  703. SSL_set_session(m_ssl, NULL);
  704. }
  705. }
  706. else
  707. {
  708. SSL_set_session(m_ssl, NULL);
  709. }
  710. if (clientMode)
  711. {
  712. SSL_set_connect_state(m_ssl);
  713. }
  714. else
  715. {
  716. SSL_set_accept_state(m_ssl);
  717. }
  718. SSL_set_bio(m_ssl, m_ibio, m_ibio);
  719. BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  720. BIO_read(m_sslbio, (void *)1, 0);
  721. // Trigger FD_WRITE so that we can initialize SSL negotiation
  722. if (GetLayerState() == connected || GetLayerState() == attached)
  723. {
  724. TriggerEvent(FD_READ, 0);
  725. TriggerEvent(FD_WRITE, 0);
  726. TriggerEvent(FD_READ, 0, TRUE);
  727. TriggerEvent(FD_WRITE, 0, TRUE);
  728. }
  729. m_bUseSSL = true;
  730. return 0;
  731. }
  732. void CAsyncSslSocketLayer::ResetSslSession()
  733. {
  734. if (m_pRetrySendBuffer)
  735. {
  736. delete [] m_pRetrySendBuffer;
  737. m_pRetrySendBuffer = 0;
  738. }
  739. m_bFailureSent = FALSE;
  740. m_bBlocking = FALSE;
  741. m_nSslAsyncNotifyId++;
  742. m_nNetworkError = 0;
  743. m_bUseSSL = FALSE;
  744. m_nVerificationResult = 0;
  745. m_nVerificationDepth = 0;
  746. m_bSslEstablished = FALSE;
  747. if (m_sslbio)
  748. {
  749. BIO_free(m_sslbio);
  750. }
  751. if (m_ssl)
  752. {
  753. SSL_set_session(m_ssl,NULL);
  754. }
  755. if (m_nbio)
  756. {
  757. BIO_free(m_nbio);
  758. }
  759. if (m_ibio)
  760. {
  761. BIO_free(m_ibio);
  762. }
  763. m_nNetworkSendBufferLen = 0;
  764. m_nbio = 0;
  765. m_ibio = 0;
  766. m_sslbio = 0;
  767. if (m_ssl)
  768. {
  769. SSL_free(m_ssl);
  770. }
  771. m_sCriticalSection.Lock();
  772. if (m_ssl_ctx)
  773. {
  774. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find(m_ssl_ctx);
  775. if (iter != m_contextRefCount.end())
  776. {
  777. if (iter->second <= 1)
  778. {
  779. SSL_CTX_free(m_ssl_ctx);
  780. m_contextRefCount.erase(iter);
  781. }
  782. else
  783. iter->second--;
  784. }
  785. m_ssl_ctx = 0;
  786. }
  787. m_ssl = 0;
  788. t_SslLayerList *cur = m_pSslLayerList;
  789. if (!cur)
  790. {
  791. m_sCriticalSection.Unlock();
  792. return;
  793. }
  794. if (cur->pLayer == this)
  795. {
  796. m_pSslLayerList = cur->pNext;
  797. delete cur;
  798. }
  799. else
  800. while (cur->pNext)
  801. {
  802. if (cur->pNext->pLayer == this)
  803. {
  804. t_SslLayerList *tmp = cur->pNext;
  805. cur->pNext = cur->pNext->pNext;
  806. delete tmp;
  807. m_sCriticalSection.Unlock();
  808. return;
  809. }
  810. cur = cur->pNext;
  811. }
  812. if (m_sessionid != NULL)
  813. {
  814. SSL_SESSION_free(m_sessionid);
  815. m_sessionid = NULL;
  816. }
  817. m_sessionreuse = true;
  818. m_sCriticalSection.Unlock();
  819. }
  820. bool CAsyncSslSocketLayer::IsUsingSSL()
  821. {
  822. return m_bUseSSL;
  823. }
  824. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  825. {
  826. if (m_bUseSSL)
  827. {
  828. if (m_pRetrySendBuffer)
  829. {
  830. if (!m_nShutDown)
  831. m_nShutDown = 1;
  832. WSASetLastError(WSAEWOULDBLOCK);
  833. return false;
  834. }
  835. if (!m_bSslEstablished)
  836. {
  837. m_mayTriggerWriteUp = true;
  838. ::SetLastError(WSAEWOULDBLOCK);
  839. return false;
  840. }
  841. if (!m_nShutDown)
  842. m_nShutDown = 1;
  843. else
  844. {
  845. if (ShutDownComplete())
  846. return ShutDownNext();
  847. else
  848. {
  849. TriggerEvents();
  850. WSASetLastError(WSAEWOULDBLOCK);
  851. return false;
  852. }
  853. }
  854. int res = SSL_shutdown(m_ssl);
  855. if (res != -1)
  856. {
  857. if (!res)
  858. {
  859. SSL_shutdown(m_ssl);
  860. }
  861. if (ShutDownComplete())
  862. return ShutDownNext();
  863. else
  864. {
  865. TriggerEvents();
  866. WSASetLastError(WSAEWOULDBLOCK);
  867. return FALSE;
  868. }
  869. }
  870. else
  871. {
  872. int error = SSL_get_error(m_ssl, -1);
  873. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  874. {
  875. // retry shutdown later
  876. m_nShutDown = 0;
  877. TriggerEvents();
  878. WSASetLastError(WSAEWOULDBLOCK);
  879. return FALSE;
  880. }
  881. else if (ShutDownComplete())
  882. return ShutDownNext();
  883. else
  884. {
  885. TriggerEvents();
  886. WSASetLastError(WSAEWOULDBLOCK);
  887. return FALSE;
  888. }
  889. }
  890. }
  891. else
  892. {
  893. if (!m_nShutDown)
  894. m_nShutDown = 1;
  895. return ShutDownNext(nHow);
  896. }
  897. }
  898. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  899. {
  900. //If a ShutDown was issued, has the connection already been shut down?
  901. if (!m_nShutDown)
  902. return FALSE;
  903. else if (!m_bUseSSL)
  904. return FALSE;
  905. else if (m_nNetworkSendBufferLen)
  906. return FALSE;
  907. else if (m_pRetrySendBuffer)
  908. return FALSE;
  909. // Empty read buffer
  910. char buffer[1000];
  911. int numread;
  912. do
  913. {
  914. numread = BIO_read(m_sslbio, buffer, 1000);
  915. } while (numread > 0);
  916. size_t pending = BIO_ctrl_pending(m_nbio);
  917. if (pending)
  918. {
  919. return FALSE;
  920. }
  921. else
  922. {
  923. return TRUE;
  924. }
  925. }
  926. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  927. {
  928. USES_CONVERSION;
  929. CAsyncSslSocketLayer *pLayer = 0;
  930. m_sCriticalSection.Lock();
  931. t_SslLayerList *cur = m_pSslLayerList;
  932. while (cur)
  933. {
  934. if (cur->pLayer->m_ssl == s)
  935. break;
  936. cur = cur->pNext;
  937. }
  938. if (!cur)
  939. {
  940. m_sCriticalSection.Unlock();
  941. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  942. return;
  943. }
  944. else
  945. pLayer = cur->pLayer;
  946. m_sCriticalSection.Unlock();
  947. // Called while unloading?
  948. if (!pLayer->m_bUseSSL && (where != SSL_CB_LOOP))
  949. return;
  950. char * str;
  951. int w;
  952. w = where& ~SSL_ST_MASK;
  953. if (w & SSL_ST_CONNECT)
  954. {
  955. str = "TLS connect";
  956. if (pLayer->m_sessionreuse)
  957. {
  958. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  959. if (pLayer->m_sessionid != sessionid)
  960. {
  961. if (pLayer->m_sessionid == NULL)
  962. {
  963. if (SSL_session_reused(pLayer->m_ssl))
  964. {
  965. pLayer->LogSocketMessageRaw(FZ_LOG_PROGRESS, L"Session ID reused");
  966. }
  967. else
  968. {
  969. if ((pLayer->m_Main != NULL) && (pLayer->m_Main->m_sessionid != NULL))
  970. {
  971. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID not reused, will not try again");
  972. SSL_SESSION_free(pLayer->m_Main->m_sessionid);
  973. pLayer->m_Main->m_sessionid = NULL;
  974. }
  975. }
  976. pLayer->LogSocketMessageRaw(FZ_LOG_DEBUG, L"Saving session ID");
  977. }
  978. else
  979. {
  980. SSL_SESSION_free(pLayer->m_sessionid);
  981. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, L"Session ID changed");
  982. }
  983. pLayer->m_sessionid = sessionid;
  984. }
  985. else
  986. {
  987. SSL_SESSION_free(sessionid);
  988. }
  989. }
  990. }
  991. else if (w & SSL_ST_ACCEPT)
  992. str = "TLS accept";
  993. else
  994. str = "Undefined";
  995. if (where & SSL_CB_LOOP)
  996. {
  997. char* debug = NULL;
  998. // exact SSL_CB_LOOP is abused for debugging
  999. if (where == SSL_CB_LOOP)
  1000. {
  1001. debug = reinterpret_cast<char*>(ret);
  1002. }
  1003. char *buffer = new char[4096 + ((debug != NULL) ? strlen(debug) : 0)];
  1004. sprintf(buffer, "%s: %s",
  1005. str,
  1006. SSL_state_string_long(s));
  1007. if (debug != NULL)
  1008. {
  1009. sprintf(buffer + strlen(buffer), " [%s]", debug);
  1010. OPENSSL_free(debug);
  1011. }
  1012. USES_CONVERSION;
  1013. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, A2T(buffer));
  1014. delete[] buffer;
  1015. }
  1016. else if (where & SSL_CB_ALERT)
  1017. {
  1018. str=(where & SSL_CB_READ)? "read" : "write";
  1019. const char* desc = SSL_alert_desc_string_long(ret);
  1020. // Don't send close notify warning
  1021. if (desc)
  1022. {
  1023. if (strcmp(desc, "close notify"))
  1024. {
  1025. char *buffer = new char[4096];
  1026. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1027. str,
  1028. SSL_alert_type_string_long(ret),
  1029. desc);
  1030. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1031. delete [] buffer;
  1032. }
  1033. }
  1034. }
  1035. else if (where & SSL_CB_EXIT)
  1036. {
  1037. if (ret == 0)
  1038. {
  1039. char *buffer = new char[4096];
  1040. sprintf(buffer, "%s: failed in %s",
  1041. str,
  1042. SSL_state_string_long(s));
  1043. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1044. delete [] buffer;
  1045. if (!pLayer->m_bFailureSent)
  1046. {
  1047. pLayer->m_bFailureSent=TRUE;
  1048. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1049. }
  1050. }
  1051. else if (ret < 0)
  1052. {
  1053. int error = SSL_get_error(s,ret);
  1054. if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
  1055. {
  1056. char *buffer = new char[4096];
  1057. sprintf(buffer, "%s: error in %s",
  1058. str,
  1059. SSL_state_string_long(s));
  1060. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1061. delete [] buffer;
  1062. if (!pLayer->m_bFailureSent)
  1063. {
  1064. pLayer->m_bFailureSent=TRUE;
  1065. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. if (where & SSL_CB_HANDSHAKE_DONE)
  1071. {
  1072. int error = SSL_get_verify_result(pLayer->m_ssl);
  1073. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERIFY_CERT, error);
  1074. pLayer->m_bBlocking = TRUE;
  1075. }
  1076. }
  1077. void CAsyncSslSocketLayer::UnloadSSL()
  1078. {
  1079. if (!m_bSslInitialized)
  1080. return;
  1081. ResetSslSession();
  1082. m_bSslInitialized = false;
  1083. m_sCriticalSection.Lock();
  1084. m_nSslRefCount--;
  1085. if (m_nSslRefCount)
  1086. {
  1087. m_sCriticalSection.Unlock();
  1088. return;
  1089. }
  1090. m_sCriticalSection.Unlock();
  1091. }
  1092. bool AsnTimeToValidTime(ASN1_TIME * AsnTime, t_SslCertData::t_validTime & ValidTime)
  1093. {
  1094. int i = AsnTime->length;
  1095. const char * v = (const char *)AsnTime->data;
  1096. if (i < 10)
  1097. {
  1098. return FALSE;
  1099. }
  1100. for (int i2 = 0; i2 < 10; i2++)
  1101. {
  1102. if ((v[i2] > '9') || (v[i2] < '0'))
  1103. {
  1104. return FALSE;
  1105. }
  1106. }
  1107. if (AsnTime->type == V_ASN1_UTCTIME)
  1108. {
  1109. ValidTime.y= (v[0]-'0')*10+(v[1]-'0');
  1110. if (ValidTime.y < 50) ValidTime.y+=100;
  1111. ValidTime.y += 1900;
  1112. v += 2;
  1113. i -= 2;
  1114. }
  1115. else if (AsnTime->type == V_ASN1_GENERALIZEDTIME)
  1116. {
  1117. if (i < 12)
  1118. {
  1119. return FALSE;
  1120. }
  1121. ValidTime.y = (v[0]-'0')*1000+(v[1]-'0')*100 + (v[2]-'0')*10+(v[3]-'0');
  1122. v += 4;
  1123. i -= 4;
  1124. }
  1125. else
  1126. {
  1127. return FALSE;
  1128. }
  1129. ValidTime.M = (v[0]-'0')*10+(v[1]-'0');
  1130. if ((ValidTime.M > 12) || (ValidTime.M < 1))
  1131. {
  1132. return FALSE;
  1133. }
  1134. ValidTime.d = (v[2]-'0')*10+(v[3]-'0');
  1135. ValidTime.h = (v[4]-'0')*10+(v[5]-'0');
  1136. ValidTime.m = (v[6]-'0')*10+(v[7]-'0');
  1137. if ((i >= 10) &&
  1138. (v[8] >= '0') && (v[8] <= '9') &&
  1139. (v[9] >= '0') && (v[9] <= '9'))
  1140. {
  1141. ValidTime.s = (v[8]-'0')*10+(v[9]-'0');
  1142. }
  1143. else
  1144. {
  1145. ValidTime.s = 0;
  1146. }
  1147. return TRUE;
  1148. }
  1149. BOOL CAsyncSslSocketLayer::GetPeerCertificateData(t_SslCertData &SslCertData, LPCTSTR & Error)
  1150. {
  1151. X509 *pX509=SSL_get_peer_certificate(m_ssl);
  1152. if (!pX509)
  1153. {
  1154. Error = L"Cannot get certificate";
  1155. return FALSE;
  1156. }
  1157. //Reset the contents of SslCertData
  1158. memset(&SslCertData, 0, sizeof(t_SslCertData));
  1159. //Set subject data fields
  1160. X509_NAME *pX509Name=X509_get_subject_name(pX509);
  1161. if (pX509Name)
  1162. {
  1163. int count=X509_NAME_entry_count(pX509Name);
  1164. for (int i=0;i<count;i++)
  1165. {
  1166. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1167. if (!pX509NameEntry)
  1168. continue;
  1169. ASN1_OBJECT *pObject = X509_NAME_ENTRY_get_object(pX509NameEntry);
  1170. ASN1_STRING *pString = X509_NAME_ENTRY_get_data(pX509NameEntry);
  1171. CString str;
  1172. unsigned char *out;
  1173. int len = ASN1_STRING_to_UTF8(&out, pString);
  1174. if (len > 0)
  1175. {
  1176. // Keep it huge
  1177. LPWSTR unicode = new WCHAR[len * 10];
  1178. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1179. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1180. if (unicodeLen > 0)
  1181. {
  1182. #ifdef _UNICODE
  1183. str = unicode;
  1184. #else
  1185. LPSTR ansi = new CHAR[len * 10];
  1186. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1187. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1188. if (ansiLen > 0)
  1189. str = ansi;
  1190. delete [] ansi;
  1191. #endif
  1192. }
  1193. delete [] unicode;
  1194. CRYPTO_free(out);
  1195. }
  1196. switch(OBJ_obj2nid(pObject))
  1197. {
  1198. case NID_organizationName:
  1199. _tcsncpy(SslCertData.subject.Organization, str, 255);
  1200. SslCertData.subject.Organization[255] = 0;
  1201. break;
  1202. case NID_organizationalUnitName:
  1203. _tcsncpy(SslCertData.subject.Unit, str, 255);
  1204. SslCertData.subject.Unit[255] = 0;
  1205. break;
  1206. case NID_commonName:
  1207. _tcsncpy(SslCertData.subject.CommonName, str, 255);
  1208. SslCertData.subject.CommonName[255] = 0;
  1209. break;
  1210. case NID_pkcs9_emailAddress:
  1211. _tcsncpy(SslCertData.subject.Mail, str, 255);
  1212. SslCertData.subject.Mail[255] = 0;
  1213. break;
  1214. case NID_countryName:
  1215. _tcsncpy(SslCertData.subject.Country, str, 255);
  1216. SslCertData.subject.Country[255] = 0;
  1217. break;
  1218. case NID_stateOrProvinceName:
  1219. _tcsncpy(SslCertData.subject.StateProvince, str, 255);
  1220. SslCertData.subject.StateProvince[255] = 0;
  1221. break;
  1222. case NID_localityName:
  1223. _tcsncpy(SslCertData.subject.Town, str, 255);
  1224. SslCertData.subject.Town[255] = 0;
  1225. break;
  1226. default:
  1227. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1228. {
  1229. TCHAR tmp[20];
  1230. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1231. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1232. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), tmp, maxlen);
  1233. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1234. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1235. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1236. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1237. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1238. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1239. }
  1240. else
  1241. {
  1242. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1243. USES_CONVERSION;
  1244. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1245. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1246. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L"=", maxlen);
  1247. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1248. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1249. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1250. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), L";", maxlen);
  1251. }
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. //Set issuer data fields
  1257. pX509Name=X509_get_issuer_name(pX509);
  1258. if (pX509Name)
  1259. {
  1260. int count=X509_NAME_entry_count(pX509Name);
  1261. for (int i=0;i<count;i++)
  1262. {
  1263. X509_NAME_ENTRY *pX509NameEntry=X509_NAME_get_entry(pX509Name,i);
  1264. if (!pX509NameEntry)
  1265. continue;
  1266. ASN1_STRING *pString=X509_NAME_ENTRY_get_data(pX509NameEntry);
  1267. ASN1_OBJECT *pObject=X509_NAME_ENTRY_get_object(pX509NameEntry);
  1268. CString str;
  1269. unsigned char *out;
  1270. int len = ASN1_STRING_to_UTF8(&out, pString);
  1271. if (len > 0)
  1272. {
  1273. // Keep it huge
  1274. LPWSTR unicode = new WCHAR[len * 10];
  1275. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1276. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1277. if (unicodeLen > 0)
  1278. {
  1279. #ifdef _UNICODE
  1280. str = unicode;
  1281. #else
  1282. LPSTR ansi = new CHAR[len * 10];
  1283. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1284. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1285. if (ansiLen > 0)
  1286. str = ansi;
  1287. delete [] ansi;
  1288. #endif
  1289. }
  1290. delete [] unicode;
  1291. CRYPTO_free(out);
  1292. }
  1293. switch(OBJ_obj2nid(pObject))
  1294. {
  1295. case NID_organizationName:
  1296. _tcsncpy(SslCertData.issuer.Organization, str, 255);
  1297. SslCertData.issuer.Organization[255] = 0;
  1298. break;
  1299. case NID_organizationalUnitName:
  1300. _tcsncpy(SslCertData.issuer.Unit, str, 255);
  1301. SslCertData.issuer.Unit[255] = 0;
  1302. break;
  1303. case NID_commonName:
  1304. _tcsncpy(SslCertData.issuer.CommonName, str, 255);
  1305. SslCertData.issuer.CommonName[255] = 0;
  1306. break;
  1307. case NID_pkcs9_emailAddress:
  1308. _tcsncpy(SslCertData.issuer.Mail, str, 255);
  1309. SslCertData.issuer.Mail[255] = 0;
  1310. break;
  1311. case NID_countryName:
  1312. _tcsncpy(SslCertData.issuer.Country, str, 255);
  1313. SslCertData.issuer.Country[255] = 0;
  1314. break;
  1315. case NID_stateOrProvinceName:
  1316. _tcsncpy(SslCertData.issuer.StateProvince, str, 255);
  1317. SslCertData.issuer.StateProvince[255] = 0;
  1318. break;
  1319. case NID_localityName:
  1320. _tcsncpy(SslCertData.issuer.Town, str, 255);
  1321. SslCertData.issuer.Town[255] = 0;
  1322. break;
  1323. default:
  1324. if ( !OBJ_nid2sn(OBJ_obj2nid(pObject)) )
  1325. {
  1326. TCHAR tmp[20];
  1327. _stprintf(tmp, L"%d", OBJ_obj2nid(pObject));
  1328. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1329. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), tmp, maxlen);
  1330. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1331. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1332. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1333. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1334. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1335. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1336. }
  1337. else
  1338. {
  1339. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1340. USES_CONVERSION;
  1341. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), A2CT(OBJ_nid2sn(OBJ_obj2nid(pObject))), maxlen);
  1342. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1343. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L"=", maxlen);
  1344. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1345. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1346. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1347. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), L";", maxlen);
  1348. }
  1349. break;
  1350. }
  1351. }
  1352. }
  1353. //Set date fields
  1354. //Valid from
  1355. ASN1_TIME *pTime=X509_get_notBefore(pX509);
  1356. if (!pTime)
  1357. {
  1358. X509_free(pX509);
  1359. Error = L"Cannot get start time";
  1360. return FALSE;
  1361. }
  1362. if (!AsnTimeToValidTime(pTime, SslCertData.validFrom))
  1363. {
  1364. X509_free(pX509);
  1365. Error = L"Invalid start time";
  1366. return FALSE;
  1367. }
  1368. //Valid until
  1369. pTime = X509_get_notAfter(pX509);
  1370. if (!pTime)
  1371. {
  1372. X509_free(pX509);
  1373. Error = L"Cannot get end time";
  1374. return FALSE;
  1375. }
  1376. if (!AsnTimeToValidTime(pTime, SslCertData.validUntil))
  1377. {
  1378. X509_free(pX509);
  1379. Error = L"Invalid end time";
  1380. return FALSE;
  1381. }
  1382. int subjectAltNamePos = X509_get_ext_by_NID(pX509, NID_subject_alt_name, -1);
  1383. if (subjectAltNamePos >= 0)
  1384. {
  1385. X509_EXTENSION * subjectAltNameExtension = X509_get_ext(pX509, subjectAltNamePos);
  1386. BIO * subjectAltNameBio = BIO_new(BIO_s_mem());
  1387. if (X509V3_EXT_print(subjectAltNameBio, subjectAltNameExtension, 0, 0) == 1)
  1388. {
  1389. USES_CONVERSION;
  1390. u_char *data;
  1391. int len = BIO_get_mem_data(subjectAltNameBio, &data);
  1392. char * buf = new char[len + 1];
  1393. memcpy(buf, data, len);
  1394. buf[len] = '\0';
  1395. _tcsncpy(SslCertData.subjectAltName, A2CT(buf), LENOF(SslCertData.subjectAltName));
  1396. SslCertData.subjectAltName[LENOF(SslCertData.subjectAltName) - 1] = '\0';
  1397. delete [] buf;
  1398. }
  1399. BIO_vfree(subjectAltNameBio);
  1400. }
  1401. unsigned int length = 20;
  1402. X509_digest(pX509, EVP_sha1(), SslCertData.hash, &length);
  1403. // Inspired by ne_ssl_cert_export()
  1404. // Find the length of the DER encoding.
  1405. SslCertData.certificateLen = i2d_X509(pX509, NULL);
  1406. SslCertData.certificate = new unsigned char[SslCertData.certificateLen];
  1407. unsigned char * p = SslCertData.certificate;
  1408. i2d_X509(pX509, &p);
  1409. SslCertData.priv_data = m_nSslAsyncNotifyId;
  1410. X509_free(pX509);
  1411. SslCertData.verificationResult = m_nVerificationResult;
  1412. SslCertData.verificationDepth = m_nVerificationDepth;
  1413. return TRUE;
  1414. }
  1415. std::string CAsyncSslSocketLayer::GetTlsVersionStr()
  1416. {
  1417. return m_TlsVersionStr;
  1418. }
  1419. std::string CAsyncSslSocketLayer::GetCipherName()
  1420. {
  1421. return m_CipherName;
  1422. }
  1423. void CAsyncSslSocketLayer::SetNotifyReply(int nID, int nCode, int result)
  1424. {
  1425. if (!m_bBlocking)
  1426. return;
  1427. if (nID != m_nSslAsyncNotifyId)
  1428. return;
  1429. if (nCode != SSL_VERIFY_CERT)
  1430. return;
  1431. m_bBlocking = FALSE;
  1432. if (!result)
  1433. {
  1434. m_nNetworkError = WSAECONNABORTED;
  1435. WSASetLastError(WSAECONNABORTED);
  1436. if (!m_bFailureSent)
  1437. {
  1438. m_bFailureSent = TRUE;
  1439. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, SSL_FAILURE_CERTREJECTED);
  1440. }
  1441. TriggerEvent(FD_CLOSE, 0, TRUE);
  1442. return;
  1443. }
  1444. m_bSslEstablished = TRUE;
  1445. PrintSessionInfo();
  1446. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_ESTABLISHED);
  1447. TriggerEvents();
  1448. }
  1449. void CAsyncSslSocketLayer::PrintSessionInfo()
  1450. {
  1451. const SSL_CIPHER *ciph;
  1452. X509 *cert;
  1453. ciph = SSL_get_current_cipher(m_ssl);
  1454. char enc[4096] = {0};
  1455. cert=SSL_get_peer_certificate(m_ssl);
  1456. if (cert != NULL)
  1457. {
  1458. EVP_PKEY *pkey = X509_get_pubkey(cert);
  1459. if (pkey != NULL)
  1460. {
  1461. if (0)
  1462. ;
  1463. #ifndef NO_RSA
  1464. else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
  1465. && pkey->pkey.rsa->n != NULL)
  1466. sprintf(enc, "%d bit RSA", BN_num_bits(pkey->pkey.rsa->n));
  1467. #endif
  1468. #ifndef NO_DSA
  1469. else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
  1470. && pkey->pkey.dsa->p != NULL)
  1471. sprintf(enc, "%d bit DSA", BN_num_bits(pkey->pkey.dsa->p));
  1472. #endif
  1473. EVP_PKEY_free(pkey);
  1474. }
  1475. X509_free(cert);
  1476. /* The SSL API does not allow us to look at temporary RSA/DH keys,
  1477. * otherwise we should print their lengths too */
  1478. }
  1479. char *buffer = new char[4096];
  1480. // see also ne_ssl_get_version and ne_ssl_get_cipher
  1481. m_TlsVersionStr = SSL_get_version(m_ssl);
  1482. sprintf(buffer, "%s: %s, %s",
  1483. SSL_CIPHER_get_version(ciph),
  1484. SSL_CIPHER_get_name(ciph),
  1485. enc);
  1486. m_CipherName = buffer;
  1487. // see TWebDAVFileSystem::CollectTLSSessionInfo()
  1488. sprintf(buffer, "Using %s, cipher %s",
  1489. m_TlsVersionStr.c_str(),
  1490. m_CipherName.c_str());
  1491. USES_CONVERSION;
  1492. LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1493. delete [] buffer;
  1494. }
  1495. void CAsyncSslSocketLayer::OnConnect(int nErrorCode)
  1496. {
  1497. if (m_bUseSSL && nErrorCode)
  1498. TriggerEvent(FD_WRITE, 0);
  1499. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  1500. }
  1501. CAsyncSslSocketLayer * CAsyncSslSocketLayer::LookupLayer(SSL * Ssl)
  1502. {
  1503. CAsyncSslSocketLayer * Result = NULL;
  1504. m_sCriticalSection.Lock();
  1505. t_SslLayerList * Cur = m_pSslLayerList;
  1506. while (Cur != NULL)
  1507. {
  1508. if (Cur->pLayer->m_ssl == Ssl)
  1509. {
  1510. break;
  1511. }
  1512. Cur = Cur->pNext;
  1513. }
  1514. m_sCriticalSection.Unlock();
  1515. if (Cur == NULL)
  1516. {
  1517. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1518. Result = NULL;
  1519. }
  1520. else
  1521. {
  1522. Result = Cur->pLayer;
  1523. }
  1524. return Result;
  1525. }
  1526. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1527. {
  1528. X509 *err_cert;
  1529. int err, depth;
  1530. SSL *ssl;
  1531. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1532. err = X509_STORE_CTX_get_error(ctx);
  1533. depth = X509_STORE_CTX_get_error_depth(ctx);
  1534. /*
  1535. * Retrieve the pointer to the SSL of the connection currently treated
  1536. * and the application specific data stored into the SSL object.
  1537. */
  1538. ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  1539. CAsyncSslSocketLayer * pLayer = LookupLayer(ssl);
  1540. if (pLayer == NULL)
  1541. {
  1542. return 1;
  1543. }
  1544. /*
  1545. * Catch a too long certificate chain. The depth limit set using
  1546. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1547. * that whenever the "depth>verify_depth" condition is met, we
  1548. * have violated the limit and want to log this error condition.
  1549. * We must do it here, because the CHAIN_TOO_LONG error would not
  1550. * be found explicitly; only errors introduced by cutting off the
  1551. * additional certificates would be logged.
  1552. */
  1553. if (depth > 10) {//mydata->verify_depth) {
  1554. preverify_ok = 0;
  1555. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1556. X509_STORE_CTX_set_error(ctx, err);
  1557. }
  1558. if (!preverify_ok)
  1559. {
  1560. if (!pLayer->m_nVerificationResult)
  1561. {
  1562. pLayer->m_nVerificationDepth = depth;
  1563. pLayer->m_nVerificationResult = err;
  1564. }
  1565. }
  1566. return 1;
  1567. }
  1568. int CAsyncSslSocketLayer::ProvideClientCert(
  1569. SSL * Ssl, X509 ** Certificate, EVP_PKEY ** PrivateKey)
  1570. {
  1571. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  1572. USES_CONVERSION;
  1573. CString Message;
  1574. Message.LoadString(NEED_CLIENT_CERTIFICATE);
  1575. char * Buffer = new char[Message.GetLength() + 1];
  1576. strcpy(Buffer, T2A(Message));
  1577. int Level;
  1578. int Result;
  1579. if ((Layer->FCertificate == NULL) || (Layer->FPrivateKey == NULL))
  1580. {
  1581. Level = FZ_LOG_WARNING;
  1582. Result = 0;
  1583. }
  1584. else
  1585. {
  1586. Level = FZ_LOG_PROGRESS;
  1587. *Certificate = X509_dup(Layer->FCertificate);
  1588. CRYPTO_add(&Layer->FPrivateKey->references, 1, CRYPTO_LOCK_EVP_PKEY);
  1589. *PrivateKey = Layer->FPrivateKey;
  1590. Result = 1;
  1591. }
  1592. Layer->LogSocketMessageRaw(Level, A2T(Buffer));
  1593. delete [] Buffer;
  1594. return Result;
  1595. }
  1596. void CAsyncSslSocketLayer::SetClientCertificate(X509 * Certificate, EVP_PKEY * PrivateKey)
  1597. {
  1598. FCertificate = Certificate;
  1599. FPrivateKey = PrivateKey;
  1600. }
  1601. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1602. {
  1603. m_CertStorage = file;
  1604. return TRUE;
  1605. }
  1606. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1607. {
  1608. m_onCloseCalled = true;
  1609. if (m_bUseSSL && BIO_ctrl)
  1610. {
  1611. size_t pending = BIO_ctrl_pending(m_sslbio);
  1612. if (pending > 0)
  1613. {
  1614. TriggerEvents();
  1615. }
  1616. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1617. }
  1618. else
  1619. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1620. }
  1621. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1622. {
  1623. int err = ERR_get_error();
  1624. while (err)
  1625. {
  1626. char *buffer = new char[512];
  1627. ERR_error_string(err, buffer);
  1628. err = ERR_get_error();
  1629. USES_CONVERSION;
  1630. LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1631. delete [] buffer;
  1632. }
  1633. }
  1634. void CAsyncSslSocketLayer::TriggerEvents()
  1635. {
  1636. size_t pending = BIO_ctrl_pending(m_nbio);
  1637. if (pending > 0)
  1638. {
  1639. if (m_mayTriggerWrite)
  1640. {
  1641. m_mayTriggerWrite = false;
  1642. TriggerEvent(FD_WRITE, 0);
  1643. }
  1644. }
  1645. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  1646. {
  1647. if (BIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  1648. {
  1649. m_mayTriggerWriteUp = false;
  1650. TriggerEvent(FD_WRITE, 0, TRUE);
  1651. }
  1652. }
  1653. if (m_bSslEstablished && BIO_ctrl_pending(m_sslbio) > 0)
  1654. {
  1655. if (m_mayTriggerReadUp && !m_bBlocking)
  1656. {
  1657. m_mayTriggerReadUp = false;
  1658. TriggerEvent(FD_READ, 0, TRUE);
  1659. }
  1660. }
  1661. else
  1662. {
  1663. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  1664. if (len > 0 && m_mayTriggerRead)
  1665. {
  1666. m_mayTriggerRead = false;
  1667. TriggerEvent(FD_READ, 0);
  1668. }
  1669. }
  1670. if (m_onCloseCalled && m_bSslEstablished)
  1671. {
  1672. if (BIO_ctrl_pending(m_sslbio) <= 0)
  1673. {
  1674. TriggerEvent(FD_CLOSE, 0, TRUE);
  1675. }
  1676. }
  1677. }
  1678. //---------------------------------------------------------------------------