AsyncSslSocketLayer.cpp 47 KB

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