AsyncSslSocketLayer.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  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. if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL))
  66. {
  67. return SSL_FAILURE_INITSSL;
  68. }
  69. }
  70. m_nSslRefCount++;
  71. m_sCriticalSection.Unlock();
  72. m_bSslInitialized = true;
  73. return 0;
  74. }
  75. void CAsyncSslSocketLayer::OnReceive(int nErrorCode)
  76. {
  77. if (m_bUseSSL)
  78. {
  79. if (m_bBlocking)
  80. {
  81. m_mayTriggerRead = true;
  82. return;
  83. }
  84. if (m_nNetworkError)
  85. {
  86. return;
  87. }
  88. char buffer[16384];
  89. m_mayTriggerRead = false;
  90. //Get number of bytes we can receive and store in the network input bio
  91. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  92. if (len > 16384)
  93. len = 16384;
  94. else if (!len)
  95. {
  96. m_mayTriggerRead = true;
  97. TriggerEvents();
  98. return;
  99. }
  100. int numread = 0;
  101. // Receive data
  102. numread = ReceiveNext(buffer, len);
  103. if (numread > 0)
  104. {
  105. //Store it in the network input bio and process data
  106. int numwritten = BIO_write(m_nbio, buffer, numread);
  107. BIO_ctrl(m_nbio, BIO_CTRL_FLUSH, 0, NULL);
  108. // I have no idea why this call is needed, but without it, connections
  109. // will stall. Perhaps it triggers some internal processing.
  110. // Also, ignore return value, don't do any error checking. This function
  111. // can report errors, even though a later call can succeed.
  112. char buffer;
  113. BIO_read(m_sslbio, &buffer, 0);
  114. }
  115. if (!numread)
  116. {
  117. if (GetLayerState() == connected)
  118. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  119. }
  120. else if (numread == SOCKET_ERROR)
  121. {
  122. int nError = GetLastError();
  123. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  124. {
  125. m_nNetworkError = GetLastError();
  126. TriggerEvent(FD_CLOSE, 0, TRUE);
  127. return;
  128. }
  129. }
  130. if (m_pRetrySendBuffer)
  131. {
  132. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  133. if (numwrite >= 0)
  134. {
  135. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  136. delete [] m_pRetrySendBuffer;
  137. m_pRetrySendBuffer = 0;
  138. }
  139. else if (numwrite == -1)
  140. {
  141. if (!BIO_should_retry(m_sslbio))
  142. {
  143. delete [] m_pRetrySendBuffer;
  144. m_pRetrySendBuffer = 0;
  145. ::SetLastError(WSAECONNABORTED);
  146. TriggerEvent(FD_CLOSE, 0, TRUE);
  147. return;
  148. }
  149. }
  150. }
  151. if (!m_nShutDown && SSL_get_shutdown(m_ssl))
  152. {
  153. size_t pending = BIO_ctrl_pending(m_sslbio);
  154. if (pending <= 0)
  155. {
  156. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  157. {
  158. if (ShutDownComplete())
  159. TriggerEvent(FD_CLOSE, 0, TRUE);
  160. }
  161. else
  162. {
  163. m_nNetworkError = WSAECONNABORTED;
  164. WSASetLastError(WSAECONNABORTED);
  165. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  166. }
  167. return;
  168. }
  169. }
  170. if (ShutDownComplete() && m_nShutDown == 1)
  171. {
  172. //Send shutdown notification if all pending data has been sent
  173. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  174. m_nShutDown++;
  175. }
  176. TriggerEvents();
  177. }
  178. else
  179. {
  180. TriggerEvent(FD_READ, nErrorCode, TRUE);
  181. }
  182. }
  183. void CAsyncSslSocketLayer::OnSend(int nErrorCode)
  184. {
  185. if (m_bUseSSL)
  186. {
  187. if (m_nNetworkError)
  188. {
  189. return;
  190. }
  191. m_mayTriggerWrite = false;
  192. //Send data in the send buffer
  193. while (m_nNetworkSendBufferLen)
  194. {
  195. int numsent = SendNext(m_pNetworkSendBuffer, m_nNetworkSendBufferLen);
  196. if (numsent == SOCKET_ERROR)
  197. {
  198. int nError = GetLastError();
  199. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  200. {
  201. m_nNetworkError = nError;
  202. TriggerEvent(FD_CLOSE, 0, TRUE);
  203. }
  204. return;
  205. }
  206. else if (!numsent)
  207. {
  208. if (GetLayerState() == connected)
  209. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  210. }
  211. if (numsent == m_nNetworkSendBufferLen)
  212. {
  213. m_nNetworkSendBufferLen = 0;
  214. }
  215. else
  216. {
  217. memmove(m_pNetworkSendBuffer, m_pNetworkSendBuffer + numsent, m_nNetworkSendBufferLen - numsent);
  218. m_nNetworkSendBufferLen -= numsent;
  219. }
  220. }
  221. //Send the data waiting in the network bio
  222. char buffer[32 * 1024];
  223. size_t len = BIO_ctrl_pending(m_nbio);
  224. int numread = BIO_read(m_nbio, buffer, std::min(len, sizeof(buffer)));
  225. if (numread <= 0)
  226. m_mayTriggerWrite = true;
  227. while (numread > 0)
  228. {
  229. int numsent = SendNext(buffer, numread);
  230. if (!numsent)
  231. {
  232. if (GetLayerState() == connected)
  233. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  234. }
  235. if (numsent == SOCKET_ERROR || numsent < numread)
  236. {
  237. if (numsent == SOCKET_ERROR)
  238. if (GetLastError() != WSAEWOULDBLOCK && GetLastError() != WSAENOTCONN)
  239. {
  240. m_nNetworkError = GetLastError();
  241. TriggerEvent(FD_CLOSE, 0, TRUE);
  242. return;
  243. }
  244. else
  245. numsent = 0;
  246. // Add all data that was retrieved from the network bio but could not be sent to the send buffer.
  247. if (m_nNetworkSendBufferMaxLen < (m_nNetworkSendBufferLen + numread - numsent))
  248. {
  249. char * tmp = m_pNetworkSendBuffer;
  250. m_nNetworkSendBufferMaxLen = static_cast<int>((m_nNetworkSendBufferLen + numread - numsent) * 1.5);
  251. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  252. if (tmp)
  253. {
  254. memcpy(m_pNetworkSendBuffer, tmp, m_nNetworkSendBufferLen);
  255. delete [] tmp;
  256. }
  257. }
  258. DebugAssert(m_pNetworkSendBuffer);
  259. memcpy(m_pNetworkSendBuffer + m_nNetworkSendBufferLen, buffer, numread-numsent);
  260. m_nNetworkSendBufferLen += numread - numsent;
  261. }
  262. if (!numsent)
  263. {
  264. break;
  265. }
  266. len = BIO_ctrl_pending(m_nbio);
  267. if (!len)
  268. {
  269. m_mayTriggerWrite = true;
  270. break;
  271. }
  272. numread = BIO_read(m_nbio, buffer, len);
  273. if (numread <= 0)
  274. {
  275. m_mayTriggerWrite = true;
  276. }
  277. }
  278. if (m_pRetrySendBuffer)
  279. {
  280. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  281. if (numwrite >= 0)
  282. {
  283. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  284. delete [] m_pRetrySendBuffer;
  285. m_pRetrySendBuffer = 0;
  286. }
  287. else if (numwrite == -1)
  288. {
  289. if (!BIO_should_retry(m_sslbio))
  290. {
  291. delete [] m_pRetrySendBuffer;
  292. m_pRetrySendBuffer = 0;
  293. ::SetLastError(WSAECONNABORTED);
  294. TriggerEvent(FD_CLOSE, 0, TRUE);
  295. return;
  296. }
  297. }
  298. }
  299. // No more data available, ask for more.
  300. TriggerEvents();
  301. if (m_nShutDown == 1 && ShutDownComplete())
  302. {
  303. //Send shutdown notification if all pending data has been sent
  304. // FileZilla3 calls ShutDownNext() here
  305. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  306. m_nShutDown++;
  307. }
  308. }
  309. else
  310. {
  311. TriggerEvent(FD_WRITE, nErrorCode, TRUE);
  312. }
  313. }
  314. int CAsyncSslSocketLayer::Send(const void* lpBuf, int nBufLen, int nFlags)
  315. {
  316. if (m_bUseSSL)
  317. {
  318. if (!lpBuf)
  319. {
  320. return 0;
  321. }
  322. if (m_bBlocking || m_pRetrySendBuffer)
  323. {
  324. m_mayTriggerWriteUp = true;
  325. ::SetLastError(WSAEWOULDBLOCK);
  326. return SOCKET_ERROR;
  327. }
  328. if (m_nNetworkError)
  329. {
  330. SetLastError(m_nNetworkError);
  331. return SOCKET_ERROR;
  332. }
  333. if (m_nShutDown)
  334. {
  335. ::SetLastError(WSAESHUTDOWN);
  336. return SOCKET_ERROR;
  337. }
  338. if (!m_bSslEstablished)
  339. {
  340. m_mayTriggerWriteUp = true;
  341. ::SetLastError(WSAEWOULDBLOCK);
  342. return SOCKET_ERROR;
  343. }
  344. if (!nBufLen)
  345. {
  346. return 0;
  347. }
  348. if (m_onCloseCalled)
  349. {
  350. TriggerEvent(FD_CLOSE, 0, TRUE);
  351. return 0;
  352. }
  353. int len = BIO_ctrl_get_write_guarantee(m_sslbio);
  354. if (nBufLen > len)
  355. nBufLen = len;
  356. if (!len)
  357. {
  358. m_mayTriggerWriteUp = true;
  359. TriggerEvents();
  360. ::SetLastError(WSAEWOULDBLOCK);
  361. }
  362. m_pRetrySendBuffer = new char[nBufLen];
  363. m_nRetrySendBufferLen = nBufLen;
  364. memcpy(m_pRetrySendBuffer, lpBuf, nBufLen);
  365. int numwrite = BIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  366. if (numwrite >= 0)
  367. {
  368. BIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  369. delete [] m_pRetrySendBuffer;
  370. m_pRetrySendBuffer = 0;
  371. }
  372. else if (numwrite == -1)
  373. {
  374. if (BIO_should_retry(m_sslbio))
  375. {
  376. if (GetLayerState() == closed)
  377. {
  378. return 0;
  379. }
  380. else if (GetLayerState() != connected)
  381. {
  382. SetLastError(m_nNetworkError);
  383. return SOCKET_ERROR;
  384. }
  385. TriggerEvents();
  386. return nBufLen;
  387. }
  388. else
  389. {
  390. delete [] m_pRetrySendBuffer;
  391. m_pRetrySendBuffer = 0;
  392. ::SetLastError(WSAECONNABORTED);
  393. }
  394. return SOCKET_ERROR;
  395. }
  396. m_mayTriggerWriteUp = true;
  397. TriggerEvents();
  398. return numwrite;
  399. }
  400. else
  401. {
  402. return SendNext(lpBuf, nBufLen, nFlags);
  403. }
  404. }
  405. int CAsyncSslSocketLayer::Receive(void* lpBuf, int nBufLen, int nFlags)
  406. {
  407. if (m_bUseSSL)
  408. {
  409. if (m_bBlocking)
  410. {
  411. m_mayTriggerReadUp = true;
  412. ::SetLastError(WSAEWOULDBLOCK);
  413. return SOCKET_ERROR;
  414. }
  415. if (m_nNetworkError)
  416. {
  417. size_t pending = BIO_ctrl_pending(m_sslbio);
  418. if (pending && !m_nShutDown)
  419. {
  420. m_mayTriggerReadUp = true;
  421. TriggerEvents();
  422. return BIO_read(m_sslbio, lpBuf,nBufLen);
  423. }
  424. WSASetLastError(m_nNetworkError);
  425. return SOCKET_ERROR;
  426. }
  427. if (m_nShutDown)
  428. {
  429. ::SetLastError(WSAESHUTDOWN);
  430. return SOCKET_ERROR;
  431. }
  432. if (!nBufLen)
  433. {
  434. return 0;
  435. }
  436. size_t pending = BIO_ctrl_pending(m_sslbio);
  437. if (!pending)
  438. {
  439. if (GetLayerState() == closed)
  440. {
  441. return 0;
  442. }
  443. if (m_onCloseCalled)
  444. {
  445. TriggerEvent(FD_CLOSE, 0, TRUE);
  446. return 0;
  447. }
  448. else if (GetLayerState() != connected)
  449. {
  450. SetLastError(m_nNetworkError);
  451. return SOCKET_ERROR;
  452. }
  453. else
  454. {
  455. if (SSL_get_shutdown(m_ssl))
  456. {
  457. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  458. {
  459. if (ShutDownComplete())
  460. {
  461. TriggerEvent(FD_CLOSE, 0, TRUE);
  462. return 0;
  463. }
  464. else
  465. WSASetLastError(WSAEWOULDBLOCK);
  466. }
  467. else
  468. {
  469. m_nNetworkError = WSAECONNABORTED;
  470. WSASetLastError(WSAECONNABORTED);
  471. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  472. }
  473. return SOCKET_ERROR;
  474. }
  475. }
  476. m_mayTriggerReadUp = true;
  477. TriggerEvents();
  478. ::SetLastError(WSAEWOULDBLOCK);
  479. return SOCKET_ERROR;
  480. }
  481. int numread = BIO_read(m_sslbio, lpBuf, nBufLen);
  482. if (!numread)
  483. {
  484. if (SSL_get_shutdown(m_ssl))
  485. {
  486. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  487. {
  488. if (ShutDownComplete())
  489. {
  490. TriggerEvent(FD_CLOSE, 0, TRUE);
  491. return 0;
  492. }
  493. else
  494. WSASetLastError(WSAEWOULDBLOCK);
  495. }
  496. else
  497. {
  498. m_nNetworkError = WSAECONNABORTED;
  499. WSASetLastError(WSAECONNABORTED);
  500. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  501. }
  502. return SOCKET_ERROR;
  503. }
  504. m_mayTriggerReadUp = true;
  505. TriggerEvents();
  506. ::SetLastError(WSAEWOULDBLOCK);
  507. return SOCKET_ERROR;
  508. }
  509. if (numread < 0)
  510. {
  511. if (!BIO_should_retry(m_sslbio))
  512. {
  513. PrintLastErrorMsg();
  514. m_nNetworkError = WSAECONNABORTED;
  515. WSASetLastError(WSAECONNABORTED);
  516. TriggerEvent(FD_CLOSE, 0, TRUE);
  517. return SOCKET_ERROR;
  518. }
  519. else
  520. {
  521. if (SSL_get_shutdown(m_ssl))
  522. {
  523. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  524. {
  525. if (ShutDownComplete())
  526. {
  527. TriggerEvent(FD_CLOSE, 0, TRUE);
  528. return 0;
  529. }
  530. else
  531. WSASetLastError(WSAEWOULDBLOCK);
  532. }
  533. else
  534. {
  535. m_nNetworkError = WSAECONNABORTED;
  536. WSASetLastError(WSAECONNABORTED);
  537. TriggerEvent(FD_CLOSE, 0, TRUE);
  538. }
  539. return SOCKET_ERROR;
  540. }
  541. m_mayTriggerReadUp = true;
  542. TriggerEvents();
  543. ::SetLastError(WSAEWOULDBLOCK);
  544. return SOCKET_ERROR;
  545. }
  546. }
  547. m_mayTriggerReadUp = true;
  548. TriggerEvents();
  549. return numread;
  550. }
  551. else
  552. {
  553. return ReceiveNext(lpBuf, nBufLen, nFlags);
  554. }
  555. }
  556. void CAsyncSslSocketLayer::Close()
  557. {
  558. m_nShutDown = 0;
  559. m_onCloseCalled = false;
  560. ResetSslSession();
  561. CloseNext();
  562. }
  563. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  564. {
  565. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  566. if (!res)
  567. {
  568. if (GetLastError() != WSAEWOULDBLOCK)
  569. {
  570. ResetSslSession();
  571. }
  572. }
  573. return res;
  574. }
  575. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  576. {
  577. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  578. if (!res)
  579. {
  580. if (GetLastError()!=WSAEWOULDBLOCK)
  581. {
  582. ResetSslSession();
  583. }
  584. }
  585. return res;
  586. }
  587. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  588. CAsyncSslSocketLayer* main, bool sessionreuse,
  589. int minTlsVersion, int maxTlsVersion,
  590. void* pSslContext /*=0*/)
  591. {
  592. if (m_bUseSSL)
  593. return 0;
  594. int res = InitSSL();
  595. if (res)
  596. return res;
  597. m_sCriticalSection.Lock();
  598. if ((SSL_CTX*)pSslContext)
  599. {
  600. if (m_ssl_ctx)
  601. {
  602. m_sCriticalSection.Unlock();
  603. ResetSslSession();
  604. return SSL_FAILURE_INITSSL;
  605. }
  606. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  607. if (iter == m_contextRefCount.end() || iter->second < 1)
  608. {
  609. m_sCriticalSection.Unlock();
  610. ResetSslSession();
  611. return SSL_FAILURE_INITSSL;
  612. }
  613. m_ssl_ctx = (SSL_CTX*)pSslContext;
  614. iter->second++;
  615. }
  616. else if (!m_ssl_ctx)
  617. {
  618. // Create new context if none given
  619. if (!(m_ssl_ctx = SSL_CTX_new( SSLv23_method())))
  620. {
  621. m_sCriticalSection.Unlock();
  622. ResetSslSession();
  623. return SSL_FAILURE_INITSSL;
  624. }
  625. m_contextRefCount[m_ssl_ctx] = 1;
  626. if (clientMode)
  627. {
  628. USES_CONVERSION;
  629. SSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  630. SSL_CTX_set_client_cert_cb(m_ssl_ctx, ProvideClientCert);
  631. CFileStatus Dummy;
  632. if (CFile::GetStatus((LPCTSTR)m_CertStorage, Dummy))
  633. {
  634. SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  635. }
  636. }
  637. }
  638. //Create new SSL session
  639. if (!(m_ssl = SSL_new(m_ssl_ctx)))
  640. {
  641. m_sCriticalSection.Unlock();
  642. ResetSslSession();
  643. return SSL_FAILURE_INITSSL;
  644. }
  645. #ifdef _DEBUG
  646. if ((main == NULL) && LoggingSocketMessage(FZ_LOG_INFO))
  647. {
  648. USES_CONVERSION;
  649. LogSocketMessageRaw(FZ_LOG_INFO, L"Supported ciphersuites:");
  650. STACK_OF(SSL_CIPHER) * ciphers = SSL_get_ciphers(m_ssl);
  651. for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); i++)
  652. {
  653. const SSL_CIPHER * cipher = sk_SSL_CIPHER_value(ciphers, i);
  654. LogSocketMessageRaw(FZ_LOG_INFO, A2CT(SSL_CIPHER_get_name(cipher)));
  655. }
  656. }
  657. #endif
  658. //Add current instance to list of active instances
  659. t_SslLayerList *tmp = m_pSslLayerList;
  660. m_pSslLayerList = new t_SslLayerList;
  661. m_pSslLayerList->pNext = tmp;
  662. m_pSslLayerList->pLayer = this;
  663. m_sCriticalSection.Unlock();
  664. SSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  665. //Create bios
  666. m_sslbio = BIO_new(BIO_f_ssl());
  667. BIO_new_bio_pair(&m_ibio, 32768, &m_nbio, 32768);
  668. if (!m_sslbio || !m_nbio || !m_ibio)
  669. {
  670. ResetSslSession();
  671. return SSL_FAILURE_INITSSL;
  672. }
  673. // See also TWebDAVFileSystem::InitSslSession
  674. #define MASK_TLS_VERSION(VERSION, FLAG) ((minTlsVersion > VERSION) || (maxTlsVersion < VERSION) ? FLAG : 0)
  675. long options =
  676. SSL_OP_ALL |
  677. MASK_TLS_VERSION(SSL_VERSION_SSL3, SSL_OP_NO_SSLv3) |
  678. MASK_TLS_VERSION(SSL_VERSION_TLS10, SSL_OP_NO_TLSv1) |
  679. MASK_TLS_VERSION(SSL_VERSION_TLS11, SSL_OP_NO_TLSv1_1) |
  680. MASK_TLS_VERSION(SSL_VERSION_TLS12, SSL_OP_NO_TLSv1_2);
  681. // adds flags (not sets)
  682. SSL_set_options(m_ssl, options);
  683. //Init SSL connection
  684. void *ssl_sessionid = NULL;
  685. m_Main = main;
  686. m_sessionreuse = sessionreuse;
  687. if ((m_Main != NULL) && m_sessionreuse)
  688. {
  689. if (m_Main->m_sessionid != NULL)
  690. {
  691. if (!SSL_set_session(m_ssl, m_Main->m_sessionid))
  692. {
  693. LogSocketMessageRaw(FZ_LOG_INFO, L"SSL_set_session failed");
  694. return SSL_FAILURE_INITSSL;
  695. }
  696. LogSocketMessageRaw(FZ_LOG_INFO, L"Trying reuse main TLS session ID");
  697. }
  698. else
  699. {
  700. LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID was not reused previously, not trying again");
  701. SSL_set_session(m_ssl, NULL);
  702. }
  703. }
  704. else
  705. {
  706. SSL_set_session(m_ssl, NULL);
  707. }
  708. if (clientMode)
  709. {
  710. SSL_set_connect_state(m_ssl);
  711. }
  712. else
  713. {
  714. SSL_set_accept_state(m_ssl);
  715. }
  716. SSL_set_bio(m_ssl, m_ibio, m_ibio);
  717. BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  718. BIO_read(m_sslbio, (void *)1, 0);
  719. // Trigger FD_WRITE so that we can initialize SSL negotiation
  720. if (GetLayerState() == connected || GetLayerState() == attached)
  721. {
  722. TriggerEvent(FD_READ, 0);
  723. TriggerEvent(FD_WRITE, 0);
  724. TriggerEvent(FD_READ, 0, TRUE);
  725. TriggerEvent(FD_WRITE, 0, TRUE);
  726. }
  727. m_bUseSSL = true;
  728. return 0;
  729. }
  730. void CAsyncSslSocketLayer::ResetSslSession()
  731. {
  732. if (m_pRetrySendBuffer)
  733. {
  734. delete [] m_pRetrySendBuffer;
  735. m_pRetrySendBuffer = 0;
  736. }
  737. m_bFailureSent = FALSE;
  738. m_bBlocking = FALSE;
  739. m_nSslAsyncNotifyId++;
  740. m_nNetworkError = 0;
  741. m_bUseSSL = FALSE;
  742. m_nVerificationResult = 0;
  743. m_nVerificationDepth = 0;
  744. m_bSslEstablished = FALSE;
  745. if (m_sslbio)
  746. {
  747. BIO_free(m_sslbio);
  748. }
  749. if (m_ssl)
  750. {
  751. SSL_set_session(m_ssl,NULL);
  752. }
  753. if (m_nbio)
  754. {
  755. BIO_free(m_nbio);
  756. }
  757. if (m_ibio)
  758. {
  759. BIO_free(m_ibio);
  760. }
  761. m_nNetworkSendBufferLen = 0;
  762. m_nbio = 0;
  763. m_ibio = 0;
  764. m_sslbio = 0;
  765. if (m_ssl)
  766. {
  767. SSL_free(m_ssl);
  768. }
  769. m_sCriticalSection.Lock();
  770. if (m_ssl_ctx)
  771. {
  772. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find(m_ssl_ctx);
  773. if (iter != m_contextRefCount.end())
  774. {
  775. if (iter->second <= 1)
  776. {
  777. SSL_CTX_free(m_ssl_ctx);
  778. m_contextRefCount.erase(iter);
  779. }
  780. else
  781. iter->second--;
  782. }
  783. m_ssl_ctx = 0;
  784. }
  785. m_ssl = 0;
  786. t_SslLayerList *cur = m_pSslLayerList;
  787. if (!cur)
  788. {
  789. m_sCriticalSection.Unlock();
  790. return;
  791. }
  792. if (cur->pLayer == this)
  793. {
  794. m_pSslLayerList = cur->pNext;
  795. delete cur;
  796. }
  797. else
  798. while (cur->pNext)
  799. {
  800. if (cur->pNext->pLayer == this)
  801. {
  802. t_SslLayerList *tmp = cur->pNext;
  803. cur->pNext = cur->pNext->pNext;
  804. delete tmp;
  805. m_sCriticalSection.Unlock();
  806. return;
  807. }
  808. cur = cur->pNext;
  809. }
  810. if (m_sessionid != NULL)
  811. {
  812. SSL_SESSION_free(m_sessionid);
  813. m_sessionid = NULL;
  814. }
  815. m_sessionreuse = true;
  816. m_sCriticalSection.Unlock();
  817. }
  818. bool CAsyncSslSocketLayer::IsUsingSSL()
  819. {
  820. return m_bUseSSL;
  821. }
  822. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  823. {
  824. if (m_bUseSSL)
  825. {
  826. if (m_pRetrySendBuffer)
  827. {
  828. if (!m_nShutDown)
  829. m_nShutDown = 1;
  830. WSASetLastError(WSAEWOULDBLOCK);
  831. return false;
  832. }
  833. if (!m_bSslEstablished)
  834. {
  835. m_mayTriggerWriteUp = true;
  836. ::SetLastError(WSAEWOULDBLOCK);
  837. return false;
  838. }
  839. if (!m_nShutDown)
  840. m_nShutDown = 1;
  841. else
  842. {
  843. if (ShutDownComplete())
  844. return ShutDownNext();
  845. else
  846. {
  847. TriggerEvents();
  848. WSASetLastError(WSAEWOULDBLOCK);
  849. return false;
  850. }
  851. }
  852. int res = SSL_shutdown(m_ssl);
  853. if (res != -1)
  854. {
  855. if (!res)
  856. {
  857. SSL_shutdown(m_ssl);
  858. }
  859. if (ShutDownComplete())
  860. return ShutDownNext();
  861. else
  862. {
  863. TriggerEvents();
  864. WSASetLastError(WSAEWOULDBLOCK);
  865. return FALSE;
  866. }
  867. }
  868. else
  869. {
  870. int error = SSL_get_error(m_ssl, -1);
  871. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  872. {
  873. // retry shutdown later
  874. m_nShutDown = 0;
  875. TriggerEvents();
  876. WSASetLastError(WSAEWOULDBLOCK);
  877. return FALSE;
  878. }
  879. else if (ShutDownComplete())
  880. return ShutDownNext();
  881. else
  882. {
  883. TriggerEvents();
  884. WSASetLastError(WSAEWOULDBLOCK);
  885. return FALSE;
  886. }
  887. }
  888. }
  889. else
  890. {
  891. if (!m_nShutDown)
  892. m_nShutDown = 1;
  893. return ShutDownNext(nHow);
  894. }
  895. }
  896. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  897. {
  898. //If a ShutDown was issued, has the connection already been shut down?
  899. if (!m_nShutDown)
  900. return FALSE;
  901. else if (!m_bUseSSL)
  902. return FALSE;
  903. else if (m_nNetworkSendBufferLen)
  904. return FALSE;
  905. else if (m_pRetrySendBuffer)
  906. return FALSE;
  907. // Empty read buffer
  908. char buffer[1000];
  909. int numread;
  910. do
  911. {
  912. numread = BIO_read(m_sslbio, buffer, 1000);
  913. } while (numread > 0);
  914. size_t pending = BIO_ctrl_pending(m_nbio);
  915. if (pending)
  916. {
  917. return FALSE;
  918. }
  919. else
  920. {
  921. return TRUE;
  922. }
  923. }
  924. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  925. {
  926. USES_CONVERSION;
  927. CAsyncSslSocketLayer *pLayer = 0;
  928. m_sCriticalSection.Lock();
  929. t_SslLayerList *cur = m_pSslLayerList;
  930. while (cur)
  931. {
  932. if (cur->pLayer->m_ssl == s)
  933. break;
  934. cur = cur->pNext;
  935. }
  936. if (!cur)
  937. {
  938. m_sCriticalSection.Unlock();
  939. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  940. return;
  941. }
  942. else
  943. pLayer = cur->pLayer;
  944. m_sCriticalSection.Unlock();
  945. // Called while unloading?
  946. if (!pLayer->m_bUseSSL && (where != SSL_CB_LOOP))
  947. return;
  948. char * str;
  949. int w;
  950. w = where& ~SSL_ST_MASK;
  951. if (w & SSL_ST_CONNECT)
  952. {
  953. str = "TLS connect";
  954. if (pLayer->m_sessionreuse)
  955. {
  956. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  957. if (pLayer->m_sessionid != sessionid)
  958. {
  959. if (pLayer->m_sessionid == NULL)
  960. {
  961. if (SSL_session_reused(pLayer->m_ssl))
  962. {
  963. pLayer->LogSocketMessageRaw(FZ_LOG_PROGRESS, L"Session ID reused");
  964. }
  965. else
  966. {
  967. if ((pLayer->m_Main != NULL) && (pLayer->m_Main->m_sessionid != NULL))
  968. {
  969. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, L"Main TLS session ID not reused, will not try again");
  970. SSL_SESSION_free(pLayer->m_Main->m_sessionid);
  971. pLayer->m_Main->m_sessionid = NULL;
  972. }
  973. }
  974. pLayer->LogSocketMessageRaw(FZ_LOG_DEBUG, L"Saving session ID");
  975. }
  976. else
  977. {
  978. SSL_SESSION_free(pLayer->m_sessionid);
  979. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, L"Session ID changed");
  980. }
  981. pLayer->m_sessionid = sessionid;
  982. }
  983. else
  984. {
  985. SSL_SESSION_free(sessionid);
  986. }
  987. }
  988. }
  989. else if (w & SSL_ST_ACCEPT)
  990. str = "TLS accept";
  991. else
  992. str = "Undefined";
  993. if (where & SSL_CB_LOOP)
  994. {
  995. char* debug = NULL;
  996. // exact SSL_CB_LOOP is abused for debugging
  997. if (where == SSL_CB_LOOP)
  998. {
  999. debug = reinterpret_cast<char*>(ret);
  1000. }
  1001. char *buffer = new char[4096 + ((debug != NULL) ? strlen(debug) : 0)];
  1002. sprintf(buffer, "%s: %s",
  1003. str,
  1004. SSL_state_string_long(s));
  1005. if (debug != NULL)
  1006. {
  1007. sprintf(buffer + strlen(buffer), " [%s]", debug);
  1008. OPENSSL_free(debug);
  1009. }
  1010. USES_CONVERSION;
  1011. pLayer->LogSocketMessageRaw(FZ_LOG_INFO, A2T(buffer));
  1012. delete[] buffer;
  1013. }
  1014. else if (where & SSL_CB_ALERT)
  1015. {
  1016. str=(where & SSL_CB_READ)? "read" : "write";
  1017. const char* desc = SSL_alert_desc_string_long(ret);
  1018. // Don't send close notify warning
  1019. if (desc)
  1020. {
  1021. if (strcmp(desc, "close notify"))
  1022. {
  1023. char *buffer = new char[4096];
  1024. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1025. str,
  1026. SSL_alert_type_string_long(ret),
  1027. desc);
  1028. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1029. pLayer->PrintLastErrorMsg();
  1030. delete [] buffer;
  1031. }
  1032. }
  1033. }
  1034. else if (where & SSL_CB_EXIT)
  1035. {
  1036. if (ret == 0)
  1037. {
  1038. char *buffer = new char[4096];
  1039. sprintf(buffer, "%s: failed in %s",
  1040. str,
  1041. SSL_state_string_long(s));
  1042. pLayer->LogSocketMessageRaw(FZ_LOG_WARNING, A2T(buffer));
  1043. pLayer->PrintLastErrorMsg();
  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. OPENSSL_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. OPENSSL_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_getm_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_getm_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 (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
  1465. sprintf(enc, "%d bit RSA", EVP_PKEY_bits(pkey));
  1466. #endif
  1467. #ifndef NO_DSA
  1468. else if (EVP_PKEY_id(pkey) == EVP_PKEY_DSA)
  1469. sprintf(enc, "%d bit DSA", EVP_PKEY_bits(pkey));
  1470. #endif
  1471. EVP_PKEY_free(pkey);
  1472. }
  1473. X509_free(cert);
  1474. /* The SSL API does not allow us to look at temporary RSA/DH keys,
  1475. * otherwise we should print their lengths too */
  1476. }
  1477. const int buffer_size = 4096;
  1478. char *buffer = new char[buffer_size];
  1479. char *buffer2 = new char[buffer_size];
  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, %s",
  1483. SSL_CIPHER_get_version(ciph),
  1484. SSL_CIPHER_get_name(ciph),
  1485. enc,
  1486. SSL_CIPHER_description(ciph, buffer2, buffer_size));
  1487. m_CipherName = buffer;
  1488. // see TWebDAVFileSystem::CollectTLSSessionInfo()
  1489. sprintf(buffer, "Using %s, cipher %s",
  1490. m_TlsVersionStr.c_str(),
  1491. m_CipherName.c_str());
  1492. USES_CONVERSION;
  1493. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1494. delete [] buffer;
  1495. delete [] buffer2;
  1496. }
  1497. void CAsyncSslSocketLayer::OnConnect(int nErrorCode)
  1498. {
  1499. if (m_bUseSSL && nErrorCode)
  1500. TriggerEvent(FD_WRITE, 0);
  1501. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  1502. }
  1503. CAsyncSslSocketLayer * CAsyncSslSocketLayer::LookupLayer(SSL * Ssl)
  1504. {
  1505. CAsyncSslSocketLayer * Result = NULL;
  1506. m_sCriticalSection.Lock();
  1507. t_SslLayerList * Cur = m_pSslLayerList;
  1508. while (Cur != NULL)
  1509. {
  1510. if (Cur->pLayer->m_ssl == Ssl)
  1511. {
  1512. break;
  1513. }
  1514. Cur = Cur->pNext;
  1515. }
  1516. m_sCriticalSection.Unlock();
  1517. if (Cur == NULL)
  1518. {
  1519. MessageBox(0, L"Can't lookup TLS session!", L"Critical error", MB_ICONEXCLAMATION);
  1520. Result = NULL;
  1521. }
  1522. else
  1523. {
  1524. Result = Cur->pLayer;
  1525. }
  1526. return Result;
  1527. }
  1528. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1529. {
  1530. X509 *err_cert;
  1531. int err, depth;
  1532. SSL *ssl;
  1533. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1534. err = X509_STORE_CTX_get_error(ctx);
  1535. depth = X509_STORE_CTX_get_error_depth(ctx);
  1536. /*
  1537. * Retrieve the pointer to the SSL of the connection currently treated
  1538. * and the application specific data stored into the SSL object.
  1539. */
  1540. ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  1541. CAsyncSslSocketLayer * pLayer = LookupLayer(ssl);
  1542. if (pLayer == NULL)
  1543. {
  1544. return 1;
  1545. }
  1546. /*
  1547. * Catch a too long certificate chain. The depth limit set using
  1548. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1549. * that whenever the "depth>verify_depth" condition is met, we
  1550. * have violated the limit and want to log this error condition.
  1551. * We must do it here, because the CHAIN_TOO_LONG error would not
  1552. * be found explicitly; only errors introduced by cutting off the
  1553. * additional certificates would be logged.
  1554. */
  1555. if (depth > 10) {//mydata->verify_depth) {
  1556. preverify_ok = 0;
  1557. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1558. X509_STORE_CTX_set_error(ctx, err);
  1559. }
  1560. if (!preverify_ok)
  1561. {
  1562. if (!pLayer->m_nVerificationResult)
  1563. {
  1564. pLayer->m_nVerificationDepth = depth;
  1565. pLayer->m_nVerificationResult = err;
  1566. }
  1567. }
  1568. return 1;
  1569. }
  1570. int CAsyncSslSocketLayer::ProvideClientCert(
  1571. SSL * Ssl, X509 ** Certificate, EVP_PKEY ** PrivateKey)
  1572. {
  1573. CAsyncSslSocketLayer * Layer = LookupLayer(Ssl);
  1574. USES_CONVERSION;
  1575. CString Message;
  1576. Message.LoadString(NEED_CLIENT_CERTIFICATE);
  1577. char * Buffer = new char[Message.GetLength() + 1];
  1578. strcpy(Buffer, T2A(Message));
  1579. int Level;
  1580. int Result;
  1581. if ((Layer->FCertificate == NULL) || (Layer->FPrivateKey == NULL))
  1582. {
  1583. Level = FZ_LOG_WARNING;
  1584. Result = 0;
  1585. }
  1586. else
  1587. {
  1588. Level = FZ_LOG_PROGRESS;
  1589. *Certificate = X509_dup(Layer->FCertificate);
  1590. EVP_PKEY_up_ref(Layer->FPrivateKey);
  1591. *PrivateKey = Layer->FPrivateKey;
  1592. Result = 1;
  1593. }
  1594. Layer->LogSocketMessageRaw(Level, A2T(Buffer));
  1595. delete [] Buffer;
  1596. return Result;
  1597. }
  1598. void CAsyncSslSocketLayer::SetClientCertificate(X509 * Certificate, EVP_PKEY * PrivateKey)
  1599. {
  1600. FCertificate = Certificate;
  1601. FPrivateKey = PrivateKey;
  1602. }
  1603. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1604. {
  1605. m_CertStorage = file;
  1606. return TRUE;
  1607. }
  1608. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1609. {
  1610. m_onCloseCalled = true;
  1611. if (m_bUseSSL && BIO_ctrl)
  1612. {
  1613. size_t pending = BIO_ctrl_pending(m_sslbio);
  1614. if (pending > 0)
  1615. {
  1616. TriggerEvents();
  1617. }
  1618. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1619. }
  1620. else
  1621. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1622. }
  1623. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1624. {
  1625. int err = ERR_get_error();
  1626. while (err)
  1627. {
  1628. char *buffer = new char[512];
  1629. const char *reason = ERR_reason_error_string(err);
  1630. ERR_error_string(err, buffer);
  1631. err = ERR_get_error();
  1632. USES_CONVERSION;
  1633. LogSocketMessageRaw(FZ_LOG_PROGRESS, A2T(buffer));
  1634. LogSocketMessageRaw(FZ_LOG_WARNING, A2T(reason));
  1635. delete [] buffer;
  1636. }
  1637. }
  1638. void CAsyncSslSocketLayer::TriggerEvents()
  1639. {
  1640. size_t pending = BIO_ctrl_pending(m_nbio);
  1641. if (pending > 0)
  1642. {
  1643. if (m_mayTriggerWrite)
  1644. {
  1645. m_mayTriggerWrite = false;
  1646. TriggerEvent(FD_WRITE, 0);
  1647. }
  1648. }
  1649. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  1650. {
  1651. if (BIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  1652. {
  1653. m_mayTriggerWriteUp = false;
  1654. TriggerEvent(FD_WRITE, 0, TRUE);
  1655. }
  1656. }
  1657. if (m_bSslEstablished && BIO_ctrl_pending(m_sslbio) > 0)
  1658. {
  1659. if (m_mayTriggerReadUp && !m_bBlocking)
  1660. {
  1661. m_mayTriggerReadUp = false;
  1662. TriggerEvent(FD_READ, 0, TRUE);
  1663. }
  1664. }
  1665. else
  1666. {
  1667. int len = BIO_ctrl_get_write_guarantee(m_nbio);
  1668. if (len > 0 && m_mayTriggerRead)
  1669. {
  1670. m_mayTriggerRead = false;
  1671. TriggerEvent(FD_READ, 0);
  1672. }
  1673. }
  1674. if (m_onCloseCalled && m_bSslEstablished)
  1675. {
  1676. if (BIO_ctrl_pending(m_sslbio) <= 0)
  1677. {
  1678. TriggerEvent(FD_CLOSE, 0, TRUE);
  1679. }
  1680. }
  1681. }
  1682. //---------------------------------------------------------------------------