AsyncSslSocketLayer.cpp 48 KB

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