AsyncSslSocketLayer.cpp 47 KB

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