AsyncSslSocketLayer.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  1. /* CAsyncSslSocketLayer by Tim Kosse
  2. mailto: [email protected])
  3. Version 2.0 (2005-02-27)
  4. -------------------------------------------------------------
  5. Introduction
  6. ------------
  7. CAsyncSslSocketLayer is a layer class for CAsyncSocketEx which allows you to establish SSL secured
  8. connections. Support for both client and server side is provided.
  9. How to use
  10. ----------
  11. Using this class is really simple. In the easiest case, just add an instance of
  12. CAsyncSslSocketLayer to your socket and call InitClientSsl after creation of the socket.
  13. This class only has a couple of public functions:
  14. - InitSSLConnection(bool clientMode);
  15. This functions establishes an SSL connection. The clientMode parameter specifies wether the SSL connection
  16. is in server or in client mode.
  17. Most likely you want to call this function right after calling Create for the socket.
  18. But sometimes, you'll need to call this function later. One example is for an FTP connection
  19. with explicit SSL: In this case you would have to call InitSSLConnection after receiving the reply
  20. to an 'AUTH SSL' command.
  21. - Is UsingSSL();
  22. Returns true if you've previously called InitClientSsl()
  23. - SetNotifyReply(SetNotifyReply(int nID, int nCode, int result);
  24. You can call this function only after receiving a layerspecific callback with the SSL_VERIFY_CERT
  25. id. Set result to 1 if you trust the certificate and 0 if you don't trust it.
  26. nID has to be the priv_data element of the t_SslCertData structure and nCode has to be SSL_VERIFY_CERT.
  27. - CreateSslCertificate(LPCTSTR filename, int bits, unsigned char* country, unsigned char* state,
  28. unsigned char* locality, unsigned char* organization, unsigned char* unit, unsigned char* cname,
  29. unsigned char *email, CString& err);
  30. Creates a new self-signed SSL certificate and stores it in the given file
  31. - SendRaw(const void* lpBuf, int nBufLen, int nFlags = 0)
  32. Sends a raw, unencrypted message. This may be useful after successful initialization to tell the other
  33. side that can use SSL.
  34. This layer sends some layerspecific notifications to your socket instance, you can handle them in
  35. OnLayerCallback of your socket class.
  36. Valid notification IDs are:
  37. - SSL_INFO 0
  38. There are two possible values for param2:
  39. SSL_INFO_ESTABLISHED 0 - You'll get this notification if the SSL negotiation was successful
  40. SSL_INFO_SHUTDOWNCOMPLETE 1 - You'll get this notification if the SSL connection has been shut
  41. down sucessfully. See below for details.
  42. - SSL_FAILURE 1
  43. This notification is sent if the SSL connection could not be established or if an existing
  44. connection failed. Valid values for param2 are:
  45. - SSL_FAILURE_UNKNOWN 0 - Details may have been sent with a SSL_VERBOSE_* notification.
  46. - SSL_FAILURE_ESTABLISH 1 - Problem during SSL negotiation
  47. - SSL_FAILURE_LOADDLLS 2
  48. - SSL_FAILURE_INITSSL 4
  49. - SSL_FAILURE_VERIFYCERT 8 - The remote SSL certificate was invalid
  50. - SSL_FAILURE_CERTREJECTED 16 - The remote SSL certificate was rejected by user
  51. - SSL_VERBOSE_WARNING 3
  52. SSL_VERBOSE_INFO 4
  53. This two notifications contain some additional information. The value given by param2 is a
  54. pointer to a null-terminated char string (char *) with some useful information.
  55. - SSL_VERIFY_CERT 2
  56. This notification is sent each time a remote certificate has to be verified.
  57. param2 is a pointer to a t_SslCertData structure which contains some information
  58. about the remote certificate.
  59. You have to set the reply to this message using the SetNotifyReply function.
  60. Be careful with closing the connection after sending data, not all data may have been sent already.
  61. Before closing the connection, you should call Shutdown() and wait for the SSL_INFO_SHUTDOWNCOMPLETE
  62. notification. This assures that all encrypted data really has been sent.
  63. License
  64. -------
  65. Feel free to use this class, as long as you don't claim that you wrote it
  66. and this copyright notice stays intact in the source files.
  67. If you want to use this class in a commercial application, a short message
  68. to [email protected] would be appreciated but is not required.
  69. This product includes software developed by the OpenSSL Project
  70. for use in the OpenSSL Toolkit. (http://www.openssl.org/)
  71. Version history
  72. ---------------
  73. Version 2.0:
  74. - Add server support
  75. - a lot of bug fixes
  76. */
  77. #include "stdafx.h"
  78. #include "AsyncSslSocketLayer.h"
  79. #if defined _DEBUG && defined _AFX
  80. #define new DEBUG_NEW
  81. #undef THIS_FILE
  82. static char THIS_FILE[] = __FILE__;
  83. #endif
  84. // Simple macro to declare function type and function pointer based on the
  85. // three given parametrs:
  86. // r - return type,
  87. // n - function name
  88. // a - argument list
  89. //
  90. // Example:
  91. // def(int, foo, (int x)) becomes the following:
  92. // typedef int (*tfoo)(int x);
  93. // static tfoo pfoo;
  94. #define def(r, n, a) \
  95. typedef r (*t##n) a; \
  96. static t##n p##n;
  97. // Macro to load the given macro from a dll:
  98. #ifdef MPEXT_NO_SSLDLL
  99. #include <openssl/err.h>
  100. #define load(dll, n) \
  101. p##n = n;
  102. #else
  103. #define load(dll, n) \
  104. p##n = (t##n) GetProcAddress(dll, #n); \
  105. if (!p##n) \
  106. bError = true;
  107. #endif
  108. //The following functions from the SSL libraries are used:
  109. def(int, SSL_state, (const SSL *s));
  110. def(const char*, SSL_state_string_long, (const SSL *s));
  111. def(void, SSL_set_info_callback, (SSL *ssl, void (*cb)(const SSL *ssl,int type,int val)));
  112. def(void, SSL_set_bio, (SSL *s, BIO *rbio, BIO *wbio));
  113. def(void, SSL_set_connect_state, (SSL *s));
  114. def(int, SSL_set_session, (SSL *to, SSL_SESSION *session));
  115. def(BIO_METHOD*, BIO_f_ssl, (void));
  116. def(SSL*, SSL_new, (SSL_CTX *ctx));
  117. #ifdef MPEXT
  118. def(SSL_CTX*, SSL_CTX_new, (const SSL_METHOD *meth));
  119. def(const SSL_METHOD*, SSLv23_method, (void));
  120. #else
  121. def(SSL_CTX*, SSL_CTX_new, (SSL_METHOD *meth));
  122. def(SSL_METHOD*, SSLv23_method, (void));
  123. #endif
  124. def(void, SSL_load_error_strings, (void));
  125. def(int, SSL_library_init, (void));
  126. def(void, SSL_CTX_free, (SSL_CTX *));
  127. def(void, SSL_free, (SSL *ssl));
  128. def(int, SSL_get_error, (const SSL *s, int retcode));
  129. def(int, SSL_shutdown, (SSL *s));
  130. def(int, SSL_get_shutdown, (const SSL *ssl));
  131. def(const char*, SSL_alert_type_string_long, (int value));
  132. def(const char*, SSL_alert_desc_string_long, (int value));
  133. def(void, SSL_CTX_set_verify, (SSL_CTX *ctx, int mode, int (*callback)(int, X509_STORE_CTX *)));
  134. def(X509_STORE*, SSL_CTX_get_cert_store, (const SSL_CTX *));
  135. def(long, SSL_get_verify_result, (const SSL *ssl));
  136. def(X509*, SSL_get_peer_certificate, (const SSL *s));
  137. def(const char*, SSL_get_version, (const SSL *ssl));
  138. #ifdef MPEXT
  139. def(const SSL_CIPHER*, SSL_get_current_cipher, (const SSL *ssl));
  140. #else
  141. def(SSL_CIPHER*, SSL_get_current_cipher, (const SSL *ssl));
  142. #endif
  143. def(const char*, SSL_CIPHER_get_name, (const SSL_CIPHER *cipher));
  144. def(char*, SSL_CIPHER_get_version, (const SSL_CIPHER *cipher));
  145. def(int, SSL_get_ex_data_X509_STORE_CTX_idx, (void));
  146. def(int, SSL_CTX_load_verify_locations, (SSL_CTX *ctx, const char *CAfile, const char *CApath));
  147. def(long, SSL_ctrl, (SSL *ssl, int cmd, long larg, void *parg));
  148. def(void, SSL_set_accept_state, (SSL *ssl));
  149. def(int, SSL_CTX_use_PrivateKey_file, (SSL_CTX *ctx, const char *file, int type));
  150. def(int, SSL_CTX_use_certificate_file, (SSL_CTX *ctx, const char *file, int type));
  151. def(int, SSL_CTX_check_private_key, (const SSL_CTX *ctx));
  152. def(void, SSL_CTX_set_default_passwd_cb, (SSL_CTX *ctx, pem_password_cb *cb));
  153. def(void, SSL_CTX_set_default_passwd_cb_userdata, (SSL_CTX *ctx, void *u));
  154. def(int, SSL_CTX_use_certificate_chain_file, (SSL_CTX *ctx, const char *file));
  155. def(size_t, BIO_ctrl_pending, (BIO *b));
  156. def(int, BIO_read, (BIO *b, void *data, int len));
  157. def(long, BIO_ctrl, (BIO *bp, int cmd, long larg, void *parg));
  158. def(int, BIO_write, (BIO *b, const void *data, int len));
  159. def(size_t, BIO_ctrl_get_write_guarantee, (BIO *b));
  160. def(int, BIO_new_bio_pair, (BIO **bio1, size_t writebuf1, BIO **bio2, size_t writebuf2));
  161. def(BIO*, BIO_new, (BIO_METHOD *type));
  162. def(int, BIO_free, (BIO *a));
  163. def(int, i2t_ASN1_OBJECT, (char *buf, int buf_len, ASN1_OBJECT *a));
  164. def(int, OBJ_obj2nid, (const ASN1_OBJECT *o));
  165. def(ASN1_OBJECT*, X509_NAME_ENTRY_get_object, (X509_NAME_ENTRY *ne));
  166. def(X509_NAME_ENTRY*, X509_NAME_get_entry, (X509_NAME *name, int loc));
  167. def(int, X509_NAME_entry_count, (X509_NAME *name));
  168. def(X509_NAME*, X509_get_subject_name, (X509 *a));
  169. def(X509_NAME*, X509_get_issuer_name, (X509 *a));
  170. def(const char*, OBJ_nid2sn, (int n));
  171. def(ASN1_STRING*, X509_NAME_ENTRY_get_data, (X509_NAME_ENTRY *ne));
  172. def(void, X509_STORE_CTX_set_error, (X509_STORE_CTX *ctx, int s));
  173. def(int, X509_digest, (const X509 *data, const EVP_MD *type, unsigned char *md, unsigned int *len));
  174. def(const EVP_MD*, EVP_sha1, (void));
  175. def(X509*, X509_STORE_CTX_get_current_cert, (X509_STORE_CTX *ctx));
  176. def(int, X509_STORE_CTX_get_error, (X509_STORE_CTX *ctx));
  177. def(void, X509_free, (X509 *a));
  178. def(EVP_PKEY*, X509_get_pubkey, (X509 *x));
  179. def(int, BN_num_bits, (const BIGNUM *a));
  180. def(void, EVP_PKEY_free, (EVP_PKEY *pkey));
  181. def(void*, X509_STORE_CTX_get_ex_data, (X509_STORE_CTX *ctx, int idx));
  182. def(char*, X509_NAME_oneline, (X509_NAME *a, char *buf, int size));
  183. def(const char*, X509_verify_cert_error_string, (long n));
  184. def(int, X509_STORE_CTX_get_error_depth, (X509_STORE_CTX *ctx));
  185. def(unsigned long, ERR_get_error, (void));
  186. #ifdef MPEXT
  187. def(char*, ERR_error_string, (unsigned long e, char *buf));
  188. #else
  189. def(const char*, ERR_error_string, (unsigned long e, char *buf));
  190. #endif
  191. def(int, ASN1_STRING_to_UTF8, (unsigned char **out, ASN1_STRING *in));
  192. def(void, CRYPTO_free, (void *p));
  193. def(RSA*, RSA_generate_key, (int bits, unsigned long e, void (*callback)(int,int,void *), void *cb_arg));
  194. def(int, X509_set_version, (X509 *x,long version));
  195. def(ASN1_TIME*, X509_gmtime_adj, (ASN1_TIME *s, long adj));
  196. def(int, X509_set_pubkey, (X509 *x, EVP_PKEY *pkey));
  197. def(int, X509_NAME_add_entry_by_txt, (X509_NAME *name, const char *field, int type, const unsigned char *bytes, int len, int loc, int set));
  198. def(int, X509_NAME_add_entry_by_NID, (X509_NAME *name, int nid, int type, unsigned char *bytes, int len, int loc, int set));
  199. def(int, X509_set_issuer_name, (X509 *x, X509_NAME *name));
  200. def(int, X509_sign, (X509 *x, EVP_PKEY *pkey, const EVP_MD *md));
  201. def(EVP_PKEY*, EVP_PKEY_new, (void));
  202. #ifdef MPEXT
  203. def(int, EVP_PKEY_assign, (EVP_PKEY *pkey, int type, void *key));
  204. #else
  205. def(int, EVP_PKEY_assign, (EVP_PKEY *pkey, int type, char *key));
  206. #endif
  207. def(X509*, X509_new, (void));
  208. def(int, ASN1_INTEGER_set, (ASN1_INTEGER *a, long v));
  209. def(ASN1_INTEGER*, X509_get_serialNumber, (X509 *x));
  210. #ifdef MPEXT
  211. def(int, PEM_ASN1_write_bio, (i2d_of_void *i2d,const char *name,BIO *bp,void *x, const EVP_CIPHER *enc,unsigned char *kstr,int klen, pem_password_cb *callback, void *u));
  212. #else
  213. def(int, PEM_ASN1_write_bio, (int (*i2d)(),const char *name,BIO *bp,char *x, const EVP_CIPHER *enc,unsigned char *kstr,int klen, pem_password_cb *callback, void *u));
  214. #endif
  215. def(int, i2d_X509, (X509 *x, unsigned char **out));
  216. def(BIO_METHOD *, BIO_s_mem, (void));
  217. def(int, i2d_PrivateKey, (EVP_PKEY *a, unsigned char **pp));
  218. // Critical section wrapper class
  219. #ifndef CCRITICALSECTIONWRAPPERINCLUDED
  220. class CCriticalSectionWrapper
  221. {
  222. public:
  223. CCriticalSectionWrapper()
  224. {
  225. m_bInitialized = TRUE;
  226. InitializeCriticalSection(&m_criticalSection);
  227. }
  228. ~CCriticalSectionWrapper()
  229. {
  230. if (m_bInitialized)
  231. DeleteCriticalSection(&m_criticalSection);
  232. m_bInitialized = FALSE;
  233. }
  234. void Lock()
  235. {
  236. if (m_bInitialized)
  237. EnterCriticalSection(&m_criticalSection);
  238. }
  239. void Unlock()
  240. {
  241. if (m_bInitialized)
  242. LeaveCriticalSection(&m_criticalSection);
  243. }
  244. protected:
  245. CRITICAL_SECTION m_criticalSection;
  246. BOOL m_bInitialized;
  247. };
  248. #define CCRITICALSECTIONWRAPPERINCLUDED
  249. #endif
  250. /////////////////////////////////////////////////////////////////////////////
  251. // CAsyncSslSocketLayer
  252. CCriticalSectionWrapper CAsyncSslSocketLayer::m_sCriticalSection;
  253. CAsyncSslSocketLayer::t_SslLayerList* CAsyncSslSocketLayer::m_pSslLayerList = 0;
  254. int CAsyncSslSocketLayer::m_nSslRefCount = 0;
  255. #ifndef MPEXT_NO_SSLDLL
  256. HMODULE CAsyncSslSocketLayer::m_hSslDll1 = 0;
  257. HMODULE CAsyncSslSocketLayer::m_hSslDll2 = 0;
  258. #endif
  259. std::map<SSL_CTX *, int> CAsyncSslSocketLayer::m_contextRefCount;
  260. CAsyncSslSocketLayer::CAsyncSslSocketLayer()
  261. {
  262. m_ssl = 0;
  263. m_sslbio = 0;
  264. m_ibio = 0;
  265. m_nbio = 0;
  266. m_ssl_ctx = 0;
  267. m_bUseSSL = false;
  268. m_bSslInitialized = FALSE;
  269. m_bSslEstablished = FALSE;
  270. m_nNetworkSendBufferLen = 0;
  271. m_nNetworkSendBufferMaxLen = 0;
  272. m_pNetworkSendBuffer = NULL;
  273. m_pRetrySendBuffer = 0;
  274. m_nRetrySendBufferLen = 0;
  275. m_nNetworkError = 0;
  276. m_nShutDown = 0;
  277. m_bBlocking = FALSE;
  278. m_nSslAsyncNotifyId = 0;
  279. m_bFailureSent = FALSE;
  280. m_nVerificationResult = 0;
  281. m_nVerificationDepth = 0;
  282. m_mayTriggerRead = true;
  283. m_mayTriggerWrite = true;
  284. m_mayTriggerReadUp = true;
  285. m_mayTriggerWriteUp = true;
  286. m_onCloseCalled = false;
  287. m_pKeyPassword = 0;
  288. m_Main = NULL;
  289. m_sessionid = NULL;
  290. m_sessionreuse = true;
  291. }
  292. CAsyncSslSocketLayer::~CAsyncSslSocketLayer()
  293. {
  294. UnloadSSL();
  295. delete [] m_pNetworkSendBuffer;
  296. delete [] m_pRetrySendBuffer;
  297. delete [] m_pKeyPassword;
  298. }
  299. int CAsyncSslSocketLayer::InitSSL()
  300. {
  301. if (m_bSslInitialized)
  302. return 0;
  303. m_sCriticalSection.Lock();
  304. if (!m_nSslRefCount)
  305. {
  306. #ifndef MPEXT_NO_SSLDLL
  307. m_hSslDll2=
  308. LoadLibrary(_T("libeay32.dll"));
  309. if (!m_hSslDll2)
  310. {
  311. if (m_hSslDll1)
  312. FreeLibrary(m_hSslDll1);
  313. m_hSslDll1=0;
  314. m_sCriticalSection.Unlock();
  315. return SSL_FAILURE_LOADDLLS;
  316. }
  317. bool bError = false;
  318. #endif
  319. load(m_hSslDll2, BIO_ctrl_pending);
  320. load(m_hSslDll2, BIO_ctrl_pending);
  321. load(m_hSslDll2, BIO_read);
  322. load(m_hSslDll2, BIO_ctrl);
  323. load(m_hSslDll2, BIO_write);
  324. load(m_hSslDll2, BIO_ctrl_get_write_guarantee);
  325. load(m_hSslDll2, BIO_new_bio_pair);
  326. load(m_hSslDll2, BIO_new);
  327. load(m_hSslDll2, BIO_free);
  328. load(m_hSslDll2, i2t_ASN1_OBJECT);
  329. load(m_hSslDll2, OBJ_obj2nid);
  330. load(m_hSslDll2, X509_NAME_ENTRY_get_object);
  331. load(m_hSslDll2, X509_NAME_get_entry);
  332. load(m_hSslDll2, X509_NAME_entry_count);
  333. load(m_hSslDll2, X509_get_subject_name);
  334. load(m_hSslDll2, X509_get_issuer_name);
  335. load(m_hSslDll2, OBJ_nid2sn);
  336. load(m_hSslDll2, X509_NAME_ENTRY_get_data);
  337. load(m_hSslDll2, X509_STORE_CTX_set_error);
  338. load(m_hSslDll2, X509_digest);
  339. load(m_hSslDll2, EVP_sha1);
  340. load(m_hSslDll2, X509_STORE_CTX_get_current_cert);
  341. load(m_hSslDll2, X509_STORE_CTX_get_error);
  342. load(m_hSslDll2, X509_free);
  343. load(m_hSslDll2, X509_get_pubkey);
  344. load(m_hSslDll2, BN_num_bits);
  345. load(m_hSslDll2, EVP_PKEY_free);
  346. load(m_hSslDll2, X509_STORE_CTX_get_ex_data);
  347. load(m_hSslDll2, X509_NAME_oneline);
  348. load(m_hSslDll2, X509_verify_cert_error_string);
  349. load(m_hSslDll2, X509_STORE_CTX_get_error_depth);
  350. load(m_hSslDll2, ERR_get_error);
  351. load(m_hSslDll2, ERR_error_string);
  352. load(m_hSslDll2, ASN1_STRING_to_UTF8);
  353. load(m_hSslDll2, CRYPTO_free);
  354. load(m_hSslDll2, RSA_generate_key);
  355. load(m_hSslDll2, X509_set_version);
  356. load(m_hSslDll2, X509_gmtime_adj);
  357. load(m_hSslDll2, X509_set_pubkey);
  358. load(m_hSslDll2, X509_NAME_add_entry_by_txt);
  359. load(m_hSslDll2, X509_NAME_add_entry_by_NID);
  360. load(m_hSslDll2, X509_set_issuer_name);
  361. load(m_hSslDll2, X509_sign);
  362. load(m_hSslDll2, EVP_PKEY_new);
  363. load(m_hSslDll2, EVP_PKEY_assign);
  364. load(m_hSslDll2, X509_new);
  365. load(m_hSslDll2, ASN1_INTEGER_set);
  366. load(m_hSslDll2, X509_get_serialNumber);
  367. load(m_hSslDll2, PEM_ASN1_write_bio);
  368. load(m_hSslDll2, i2d_X509);
  369. load(m_hSslDll2, BIO_s_mem);
  370. load(m_hSslDll2, i2d_PrivateKey);
  371. #ifndef MPEXT_NO_SSLDLL
  372. if (bError)
  373. {
  374. FreeLibrary(m_hSslDll1);
  375. m_hSslDll1 = 0;
  376. FreeLibrary(m_hSslDll2);
  377. m_hSslDll2 = 0;
  378. m_sCriticalSection.Unlock();
  379. return SSL_FAILURE_LOADDLLS;
  380. }
  381. m_hSslDll1 = LoadLibrary(_T("ssleay32.dll"));
  382. if (!m_hSslDll1)
  383. {
  384. if (m_hSslDll2)
  385. FreeLibrary(m_hSslDll2);
  386. m_hSslDll2 = NULL;
  387. m_sCriticalSection.Unlock();
  388. return SSL_FAILURE_LOADDLLS;
  389. }
  390. #endif
  391. load(m_hSslDll1, SSL_state_string_long);
  392. load(m_hSslDll1, SSL_state);
  393. load(m_hSslDll1, SSL_set_info_callback);
  394. load(m_hSslDll1, SSL_set_bio);
  395. load(m_hSslDll1, SSL_set_connect_state);
  396. load(m_hSslDll1, SSL_set_session);
  397. load(m_hSslDll1, BIO_f_ssl);
  398. load(m_hSslDll1, SSL_new);
  399. load(m_hSslDll1, SSL_CTX_new);
  400. load(m_hSslDll1, SSLv23_method);
  401. load(m_hSslDll1, SSL_load_error_strings);
  402. load(m_hSslDll1, SSL_library_init);
  403. load(m_hSslDll1, SSL_CTX_free);
  404. load(m_hSslDll1, SSL_free);
  405. load(m_hSslDll1, SSL_get_error);
  406. load(m_hSslDll1, SSL_shutdown);
  407. load(m_hSslDll1, SSL_get_shutdown);
  408. load(m_hSslDll1, SSL_alert_type_string_long);
  409. load(m_hSslDll1, SSL_alert_desc_string_long);
  410. load(m_hSslDll1, SSL_CTX_set_verify);
  411. load(m_hSslDll1, SSL_CTX_get_cert_store);
  412. load(m_hSslDll1, SSL_get_verify_result);
  413. load(m_hSslDll1, SSL_get_peer_certificate);
  414. load(m_hSslDll1, SSL_get_version);
  415. load(m_hSslDll1, SSL_get_current_cipher);
  416. load(m_hSslDll1, SSL_CIPHER_get_name);
  417. load(m_hSslDll1, SSL_CIPHER_get_version);
  418. load(m_hSslDll1, SSL_get_ex_data_X509_STORE_CTX_idx);
  419. load(m_hSslDll1, SSL_CTX_load_verify_locations);
  420. load(m_hSslDll1, SSL_ctrl);
  421. load(m_hSslDll1, SSL_set_accept_state);
  422. load(m_hSslDll1, SSL_CTX_use_PrivateKey_file);
  423. load(m_hSslDll1, SSL_CTX_use_certificate_file);
  424. load(m_hSslDll1, SSL_CTX_check_private_key);
  425. load(m_hSslDll1, SSL_CTX_set_default_passwd_cb_userdata);
  426. load(m_hSslDll1, SSL_CTX_set_default_passwd_cb);
  427. load(m_hSslDll1, SSL_CTX_use_certificate_chain_file);
  428. #ifndef MPEXT_NO_SSLDLL
  429. if (bError)
  430. {
  431. FreeLibrary(m_hSslDll1);
  432. m_hSslDll1=0;
  433. if (m_hSslDll2)
  434. FreeLibrary(m_hSslDll2);
  435. m_hSslDll2=0;
  436. m_sCriticalSection.Unlock();
  437. return SSL_FAILURE_LOADDLLS;
  438. }
  439. #endif
  440. pSSL_load_error_strings();
  441. if (!pSSL_library_init())
  442. {
  443. #ifndef MPEXT_NO_SSLDLL
  444. FreeLibrary(m_hSslDll1);
  445. m_hSslDll1=0;
  446. FreeLibrary(m_hSslDll2);
  447. m_hSslDll2=0;
  448. m_sCriticalSection.Unlock();
  449. #endif
  450. return SSL_FAILURE_INITSSL;
  451. }
  452. }
  453. m_nSslRefCount++;
  454. m_sCriticalSection.Unlock();
  455. m_bSslInitialized = true;
  456. return 0;
  457. }
  458. void CAsyncSslSocketLayer::OnReceive(int nErrorCode)
  459. {
  460. if (m_bUseSSL)
  461. {
  462. if (m_bBlocking)
  463. {
  464. m_mayTriggerRead = true;
  465. return;
  466. }
  467. if (m_nNetworkError)
  468. return;
  469. char buffer[16384];
  470. m_mayTriggerRead = false;
  471. //Get number of bytes we can receive and store in the network input bio
  472. int len = pBIO_ctrl_get_write_guarantee(m_nbio);
  473. if (len > 16384)
  474. len = 16384;
  475. else if (!len)
  476. {
  477. m_mayTriggerRead = true;
  478. TriggerEvents();
  479. return;
  480. }
  481. int numread = 0;
  482. // Receive data
  483. numread = ReceiveNext(buffer, len);
  484. if (numread > 0)
  485. {
  486. //Store it in the network input bio and process data
  487. int numwritten = pBIO_write(m_nbio, buffer, numread);
  488. pBIO_ctrl(m_nbio, BIO_CTRL_FLUSH, 0, NULL);
  489. // I have no idea why this call is needed, but without it, connections
  490. // will stall. Perhaps it triggers some internal processing.
  491. // Also, ignore return value, don't do any error checking. This function
  492. // can report errors, even though a later call can succeed.
  493. char buffer;
  494. pBIO_read(m_sslbio, &buffer, 0);
  495. }
  496. if (!numread)
  497. {
  498. if (GetLayerState() == connected)
  499. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  500. }
  501. else if (numread == SOCKET_ERROR)
  502. {
  503. int nError = GetLastError();
  504. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  505. {
  506. m_nNetworkError = GetLastError();
  507. TriggerEvent(FD_CLOSE, 0, TRUE);
  508. return;
  509. }
  510. }
  511. if (m_pRetrySendBuffer)
  512. {
  513. int numwrite = pBIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  514. if (numwrite >= 0)
  515. {
  516. pBIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  517. delete [] m_pRetrySendBuffer;
  518. m_pRetrySendBuffer = 0;
  519. }
  520. else if (numwrite == -1)
  521. {
  522. if (!BIO_should_retry(m_sslbio))
  523. {
  524. delete [] m_pRetrySendBuffer;
  525. m_pRetrySendBuffer = 0;
  526. SetLastError(WSAECONNABORTED);
  527. TriggerEvent(FD_CLOSE, 0, TRUE);
  528. return;
  529. }
  530. }
  531. }
  532. if (!m_nShutDown && pSSL_get_shutdown(m_ssl))
  533. {
  534. if (pBIO_ctrl_pending(m_sslbio) <= 0)
  535. {
  536. if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
  537. {
  538. if (ShutDownComplete())
  539. TriggerEvent(FD_CLOSE, 0, TRUE);
  540. }
  541. else
  542. {
  543. m_nNetworkError = WSAECONNABORTED;
  544. WSASetLastError(WSAECONNABORTED);
  545. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  546. }
  547. return;
  548. }
  549. }
  550. if (ShutDownComplete() && m_nShutDown == 1)
  551. {
  552. //Send shutdown notification if all pending data has been sent
  553. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  554. m_nShutDown++;
  555. }
  556. TriggerEvents();
  557. }
  558. else
  559. TriggerEvent(FD_READ, nErrorCode, TRUE);
  560. }
  561. void CAsyncSslSocketLayer::OnSend(int nErrorCode)
  562. {
  563. if (m_bUseSSL)
  564. {
  565. if (m_nNetworkError)
  566. return;
  567. m_mayTriggerWrite = false;
  568. //Send data in the send buffer
  569. while (m_nNetworkSendBufferLen)
  570. {
  571. int numsent = SendNext(m_pNetworkSendBuffer, m_nNetworkSendBufferLen);
  572. if (numsent == SOCKET_ERROR)
  573. {
  574. int nError = GetLastError();
  575. if (nError != WSAEWOULDBLOCK && nError != WSAENOTCONN)
  576. {
  577. m_nNetworkError = nError;
  578. TriggerEvent(FD_CLOSE, 0, TRUE);
  579. }
  580. return;
  581. }
  582. else if (!numsent)
  583. {
  584. if (GetLayerState() == connected)
  585. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  586. }
  587. if (numsent == m_nNetworkSendBufferLen)
  588. m_nNetworkSendBufferLen = 0;
  589. else
  590. {
  591. memmove(m_pNetworkSendBuffer, m_pNetworkSendBuffer + numsent, m_nNetworkSendBufferLen - numsent);
  592. m_nNetworkSendBufferLen -= numsent;
  593. }
  594. }
  595. //Send the data waiting in the network bio
  596. char buffer[16384];
  597. int len = pBIO_ctrl_pending(m_nbio);
  598. int numread = pBIO_read(m_nbio, buffer, len);
  599. if (numread <= 0)
  600. m_mayTriggerWrite = true;
  601. while (numread > 0)
  602. {
  603. int numsent = SendNext(buffer, numread);
  604. if (!numsent)
  605. {
  606. if (GetLayerState() == connected)
  607. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  608. }
  609. if (numsent == SOCKET_ERROR || numsent < numread)
  610. {
  611. if (numsent == SOCKET_ERROR)
  612. if (GetLastError() != WSAEWOULDBLOCK && GetLastError() != WSAENOTCONN)
  613. {
  614. m_nNetworkError = GetLastError();
  615. TriggerEvent(FD_CLOSE, 0, TRUE);
  616. return;
  617. }
  618. else
  619. numsent = 0;
  620. // Add all data that was retrieved from the network bio but could not be sent to the send buffer.
  621. if (m_nNetworkSendBufferMaxLen < (m_nNetworkSendBufferLen + numread - numsent))
  622. {
  623. char * tmp = m_pNetworkSendBuffer;
  624. m_nNetworkSendBufferMaxLen = static_cast<int>((m_nNetworkSendBufferLen + numread - numsent) * 1.5);
  625. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  626. if (tmp)
  627. {
  628. memcpy(m_pNetworkSendBuffer, tmp, m_nNetworkSendBufferLen);
  629. delete [] tmp;
  630. }
  631. }
  632. ASSERT(m_pNetworkSendBuffer);
  633. memcpy(m_pNetworkSendBuffer + m_nNetworkSendBufferLen, buffer, numread-numsent);
  634. m_nNetworkSendBufferLen += numread - numsent;
  635. }
  636. if (!numsent)
  637. break;
  638. len = pBIO_ctrl_pending(m_nbio);
  639. if (!len)
  640. {
  641. m_mayTriggerWrite = true;
  642. break;
  643. }
  644. numread = pBIO_read(m_nbio, buffer, len);
  645. if (numread <= 0)
  646. m_mayTriggerWrite = true;
  647. }
  648. if (m_pRetrySendBuffer)
  649. {
  650. int numwrite = pBIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  651. if (numwrite >= 0)
  652. {
  653. pBIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  654. delete [] m_pRetrySendBuffer;
  655. m_pRetrySendBuffer = 0;
  656. }
  657. else if (numwrite == -1)
  658. {
  659. if (!BIO_should_retry(m_sslbio))
  660. {
  661. delete [] m_pRetrySendBuffer;
  662. m_pRetrySendBuffer = 0;
  663. SetLastError(WSAECONNABORTED);
  664. TriggerEvent(FD_CLOSE, 0, TRUE);
  665. return;
  666. }
  667. }
  668. }
  669. // No more data available, ask for more.
  670. TriggerEvents();
  671. if (m_nShutDown == 1 && ShutDownComplete())
  672. {
  673. //Send shutdown notification if all pending data has been sent
  674. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_SHUTDOWNCOMPLETE);
  675. m_nShutDown++;
  676. }
  677. }
  678. else
  679. TriggerEvent(FD_WRITE, nErrorCode, TRUE);
  680. }
  681. int CAsyncSslSocketLayer::Send(const void* lpBuf, int nBufLen, int nFlags)
  682. {
  683. if (m_bUseSSL)
  684. {
  685. if (!lpBuf)
  686. {
  687. return 0;
  688. }
  689. if (m_bBlocking || m_pRetrySendBuffer)
  690. {
  691. m_mayTriggerWriteUp = true;
  692. SetLastError(WSAEWOULDBLOCK);
  693. return SOCKET_ERROR;
  694. }
  695. if (m_nNetworkError)
  696. {
  697. SetLastError(m_nNetworkError);
  698. return SOCKET_ERROR;
  699. }
  700. if (m_nShutDown)
  701. {
  702. SetLastError(WSAESHUTDOWN);
  703. return SOCKET_ERROR;
  704. }
  705. if (!m_bSslEstablished)
  706. {
  707. m_mayTriggerWriteUp = true;
  708. SetLastError(WSAEWOULDBLOCK);
  709. return SOCKET_ERROR;
  710. }
  711. if (!nBufLen)
  712. {
  713. return 0;
  714. }
  715. if (m_onCloseCalled)
  716. {
  717. TriggerEvent(FD_CLOSE, 0, TRUE);
  718. return 0;
  719. }
  720. int len = pBIO_ctrl_get_write_guarantee(m_sslbio);
  721. if (nBufLen > len)
  722. nBufLen = len;
  723. if (!len)
  724. {
  725. m_mayTriggerWriteUp = true;
  726. TriggerEvents();
  727. SetLastError(WSAEWOULDBLOCK);
  728. }
  729. m_pRetrySendBuffer = new char[nBufLen];
  730. m_nRetrySendBufferLen = nBufLen;
  731. memcpy(m_pRetrySendBuffer, lpBuf, nBufLen);
  732. int numwrite = pBIO_write(m_sslbio, m_pRetrySendBuffer, m_nRetrySendBufferLen);
  733. if (numwrite >= 0)
  734. {
  735. pBIO_ctrl(m_sslbio, BIO_CTRL_FLUSH, 0, NULL);
  736. delete [] m_pRetrySendBuffer;
  737. m_pRetrySendBuffer = 0;
  738. }
  739. else if (numwrite == -1)
  740. {
  741. if (BIO_should_retry(m_sslbio))
  742. {
  743. if (GetLayerState() == closed)
  744. {
  745. return 0;
  746. }
  747. else if (GetLayerState() != connected)
  748. {
  749. SetLastError(m_nNetworkError);
  750. return SOCKET_ERROR;
  751. }
  752. TriggerEvents();
  753. return nBufLen;
  754. }
  755. else
  756. {
  757. delete [] m_pRetrySendBuffer;
  758. m_pRetrySendBuffer = 0;
  759. SetLastError(WSAECONNABORTED);
  760. }
  761. return SOCKET_ERROR;
  762. }
  763. m_mayTriggerWriteUp = true;
  764. TriggerEvents();
  765. return numwrite;
  766. }
  767. else
  768. {
  769. return SendNext(lpBuf, nBufLen, nFlags);
  770. }
  771. }
  772. int CAsyncSslSocketLayer::Receive(void* lpBuf, int nBufLen, int nFlags)
  773. {
  774. if (m_bUseSSL)
  775. {
  776. if (m_bBlocking)
  777. {
  778. m_mayTriggerReadUp = true;
  779. SetLastError(WSAEWOULDBLOCK);
  780. return SOCKET_ERROR;
  781. }
  782. if (m_nNetworkError)
  783. {
  784. if (pBIO_ctrl(m_sslbio, BIO_CTRL_PENDING, 0, NULL) && !m_nShutDown)
  785. {
  786. m_mayTriggerReadUp = true;
  787. TriggerEvents();
  788. return pBIO_read(m_sslbio, lpBuf,nBufLen);
  789. }
  790. WSASetLastError(m_nNetworkError);
  791. return SOCKET_ERROR;
  792. }
  793. if (m_nShutDown)
  794. {
  795. SetLastError(WSAESHUTDOWN);
  796. return SOCKET_ERROR;
  797. }
  798. if (!nBufLen)
  799. {
  800. return 0;
  801. }
  802. if (!pBIO_ctrl(m_sslbio, BIO_CTRL_PENDING, 0, NULL))
  803. {
  804. if (GetLayerState() == closed)
  805. {
  806. return 0;
  807. }
  808. if (m_onCloseCalled)
  809. {
  810. TriggerEvent(FD_CLOSE, 0, TRUE);
  811. return 0;
  812. }
  813. else if (GetLayerState() != connected)
  814. {
  815. SetLastError(m_nNetworkError);
  816. return SOCKET_ERROR;
  817. }
  818. else
  819. {
  820. if (pSSL_get_shutdown(m_ssl))
  821. {
  822. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  823. {
  824. if (ShutDownComplete())
  825. {
  826. TriggerEvent(FD_CLOSE, 0, TRUE);
  827. return 0;
  828. }
  829. else
  830. WSASetLastError(WSAEWOULDBLOCK);
  831. }
  832. else
  833. {
  834. m_nNetworkError = WSAECONNABORTED;
  835. WSASetLastError(WSAECONNABORTED);
  836. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  837. }
  838. return SOCKET_ERROR;
  839. }
  840. }
  841. m_mayTriggerReadUp = true;
  842. TriggerEvents();
  843. SetLastError(WSAEWOULDBLOCK);
  844. return SOCKET_ERROR;
  845. }
  846. int numread = pBIO_read(m_sslbio, lpBuf, nBufLen);
  847. if (!numread)
  848. {
  849. if (pSSL_get_shutdown(m_ssl))
  850. {
  851. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  852. {
  853. if (ShutDownComplete())
  854. {
  855. TriggerEvent(FD_CLOSE, 0, TRUE);
  856. return 0;
  857. }
  858. else
  859. WSASetLastError(WSAEWOULDBLOCK);
  860. }
  861. else
  862. {
  863. m_nNetworkError = WSAECONNABORTED;
  864. WSASetLastError(WSAECONNABORTED);
  865. TriggerEvent(FD_CLOSE, WSAECONNABORTED, TRUE);
  866. }
  867. return SOCKET_ERROR;
  868. }
  869. m_mayTriggerReadUp = true;
  870. TriggerEvents();
  871. SetLastError(WSAEWOULDBLOCK);
  872. return SOCKET_ERROR;
  873. }
  874. if (numread < 0)
  875. {
  876. if (!BIO_should_retry(m_sslbio))
  877. {
  878. PrintLastErrorMsg();
  879. m_nNetworkError = WSAECONNABORTED;
  880. WSASetLastError(WSAECONNABORTED);
  881. TriggerEvent(FD_CLOSE, 0, TRUE);
  882. return SOCKET_ERROR;
  883. }
  884. else
  885. {
  886. if (pSSL_get_shutdown(m_ssl))
  887. {
  888. if (ShutDown() || GetLastError() == WSAEWOULDBLOCK)
  889. {
  890. if (ShutDownComplete())
  891. {
  892. TriggerEvent(FD_CLOSE, 0, TRUE);
  893. return 0;
  894. }
  895. else
  896. WSASetLastError(WSAEWOULDBLOCK);
  897. }
  898. else
  899. {
  900. m_nNetworkError = WSAECONNABORTED;
  901. WSASetLastError(WSAECONNABORTED);
  902. TriggerEvent(FD_CLOSE, 0, TRUE);
  903. }
  904. return SOCKET_ERROR;
  905. }
  906. m_mayTriggerReadUp = true;
  907. TriggerEvents();
  908. SetLastError(WSAEWOULDBLOCK);
  909. return SOCKET_ERROR;
  910. }
  911. }
  912. m_mayTriggerReadUp = true;
  913. TriggerEvents();
  914. return numread;
  915. }
  916. else
  917. {
  918. return ReceiveNext(lpBuf, nBufLen, nFlags);
  919. }
  920. }
  921. void CAsyncSslSocketLayer::Close()
  922. {
  923. m_nShutDown = 0;
  924. m_onCloseCalled = false;
  925. ResetSslSession();
  926. CloseNext();
  927. }
  928. BOOL CAsyncSslSocketLayer::Connect(const SOCKADDR *lpSockAddr, int nSockAddrLen)
  929. {
  930. BOOL res = ConnectNext(lpSockAddr, nSockAddrLen);
  931. if (!res)
  932. if (GetLastError() != WSAEWOULDBLOCK)
  933. ResetSslSession();
  934. return res;
  935. }
  936. BOOL CAsyncSslSocketLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  937. {
  938. BOOL res = ConnectNext(lpszHostAddress, nHostPort);
  939. if (!res)
  940. if (GetLastError()!=WSAEWOULDBLOCK)
  941. ResetSslSession();
  942. return res;
  943. }
  944. int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode,
  945. CAsyncSslSocketLayer* main, bool sessionreuse,
  946. void* pSslContext /*=0*/)
  947. {
  948. if (m_bUseSSL)
  949. return 0;
  950. int res = InitSSL();
  951. if (res)
  952. return res;
  953. m_sCriticalSection.Lock();
  954. if ((SSL_CTX*)pSslContext)
  955. {
  956. if (m_ssl_ctx)
  957. {
  958. m_sCriticalSection.Unlock();
  959. ResetSslSession();
  960. return SSL_FAILURE_INITSSL;
  961. }
  962. #ifdef MPEXT
  963. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  964. #else
  965. std::map<SSL_CTX *, int>::iterator& iter = m_contextRefCount.find((SSL_CTX*)pSslContext);
  966. #endif
  967. if (iter == m_contextRefCount.end() || iter->second < 1)
  968. {
  969. m_sCriticalSection.Unlock();
  970. ResetSslSession();
  971. return SSL_FAILURE_INITSSL;
  972. }
  973. m_ssl_ctx = (SSL_CTX*)pSslContext;
  974. iter->second++;
  975. }
  976. else if (!m_ssl_ctx)
  977. {
  978. // Create new context if none given
  979. if (!(m_ssl_ctx = pSSL_CTX_new( pSSLv23_method())))
  980. {
  981. m_sCriticalSection.Unlock();
  982. ResetSslSession();
  983. return SSL_FAILURE_INITSSL;
  984. }
  985. m_contextRefCount[m_ssl_ctx] = 1;
  986. if (clientMode)
  987. {
  988. USES_CONVERSION;
  989. pSSL_CTX_set_verify(m_ssl_ctx, SSL_VERIFY_PEER, verify_callback);
  990. pSSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0);
  991. }
  992. }
  993. //Create new SSL session
  994. if (!(m_ssl = pSSL_new(m_ssl_ctx)))
  995. {
  996. m_sCriticalSection.Unlock();
  997. ResetSslSession();
  998. return SSL_FAILURE_INITSSL;
  999. }
  1000. //Add current instance to list of active instances
  1001. t_SslLayerList *tmp = m_pSslLayerList;
  1002. m_pSslLayerList = new t_SslLayerList;
  1003. m_pSslLayerList->pNext = tmp;
  1004. m_pSslLayerList->pLayer = this;
  1005. m_sCriticalSection.Unlock();
  1006. pSSL_set_info_callback(m_ssl, apps_ssl_info_callback);
  1007. //Create bios
  1008. m_sslbio = pBIO_new(pBIO_f_ssl());
  1009. pBIO_new_bio_pair(&m_ibio, 4096, &m_nbio, 4096);
  1010. if (!m_sslbio || !m_nbio || !m_ibio)
  1011. {
  1012. ResetSslSession();
  1013. return SSL_FAILURE_INITSSL;
  1014. }
  1015. long options = pSSL_ctrl(m_ssl, SSL_CTRL_OPTIONS, 0, NULL);
  1016. options |= SSL_OP_ALL;
  1017. pSSL_ctrl(m_ssl, SSL_CTRL_OPTIONS, options, NULL);
  1018. //Init SSL connection
  1019. void *ssl_sessionid = NULL;
  1020. {
  1021. USES_CONVERSION;
  1022. m_Main = main;
  1023. m_sessionreuse = sessionreuse;
  1024. }
  1025. if ((m_Main != NULL) && m_sessionreuse)
  1026. {
  1027. if (m_Main->m_sessionid != NULL)
  1028. {
  1029. if (!pSSL_set_session(m_ssl, m_Main->m_sessionid))
  1030. {
  1031. LogSocketMessage(FZ_LOG_INFO, _T("SSL_set_session failed"));
  1032. return SSL_FAILURE_INITSSL;
  1033. }
  1034. LogSocketMessage(FZ_LOG_INFO, _T("Trying reuse main SSL session ID"));
  1035. }
  1036. else
  1037. {
  1038. LogSocketMessage(FZ_LOG_INFO, _T("Main SSL session ID was not reused previously, not trying again"));
  1039. pSSL_set_session(m_ssl, NULL);
  1040. }
  1041. }
  1042. else
  1043. {
  1044. pSSL_set_session(m_ssl, NULL);
  1045. }
  1046. if (clientMode)
  1047. {
  1048. pSSL_set_connect_state(m_ssl);
  1049. }
  1050. else
  1051. {
  1052. pSSL_set_accept_state(m_ssl);
  1053. }
  1054. pSSL_set_bio(m_ssl, m_ibio, m_ibio);
  1055. pBIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl);
  1056. pBIO_read(m_sslbio, (void *)1, 0);
  1057. // Trigger FD_WRITE so that we can initialize SSL negotiation
  1058. if (GetLayerState() == connected || GetLayerState() == attached)
  1059. {
  1060. TriggerEvent(FD_READ, 0);
  1061. TriggerEvent(FD_WRITE, 0);
  1062. TriggerEvent(FD_READ, 0, TRUE);
  1063. TriggerEvent(FD_WRITE, 0, TRUE);
  1064. }
  1065. m_bUseSSL = true;
  1066. return 0;
  1067. }
  1068. void CAsyncSslSocketLayer::ResetSslSession()
  1069. {
  1070. if (m_pRetrySendBuffer)
  1071. {
  1072. delete [] m_pRetrySendBuffer;
  1073. m_pRetrySendBuffer = 0;
  1074. }
  1075. m_bFailureSent = FALSE;
  1076. m_bBlocking = FALSE;
  1077. m_nSslAsyncNotifyId++;
  1078. m_nNetworkError = 0;
  1079. m_bUseSSL = FALSE;
  1080. m_nVerificationResult = 0;
  1081. m_nVerificationDepth = 0;
  1082. m_bSslEstablished = FALSE;
  1083. if (m_sslbio)
  1084. {
  1085. pBIO_free(m_sslbio);
  1086. }
  1087. if (m_ssl)
  1088. {
  1089. pSSL_set_session(m_ssl,NULL);
  1090. }
  1091. if (m_nbio)
  1092. {
  1093. pBIO_free(m_nbio);
  1094. }
  1095. if (m_ibio)
  1096. {
  1097. pBIO_free(m_ibio);
  1098. }
  1099. m_nNetworkSendBufferLen = 0;
  1100. m_nbio = 0;
  1101. m_ibio = 0;
  1102. m_sslbio = 0;
  1103. if (m_ssl)
  1104. {
  1105. pSSL_free(m_ssl);
  1106. }
  1107. m_sCriticalSection.Lock();
  1108. if (m_ssl_ctx)
  1109. {
  1110. #ifdef MPEXT
  1111. std::map<SSL_CTX *, int>::iterator iter = m_contextRefCount.find(m_ssl_ctx);
  1112. #else
  1113. std::map<SSL_CTX *, int>::iterator& iter = m_contextRefCount.find(m_ssl_ctx);
  1114. #endif
  1115. if (iter != m_contextRefCount.end())
  1116. {
  1117. if (iter->second <= 1)
  1118. {
  1119. pSSL_CTX_free(m_ssl_ctx);
  1120. m_contextRefCount.erase(iter);
  1121. }
  1122. else
  1123. iter->second--;
  1124. }
  1125. m_ssl_ctx = 0;
  1126. }
  1127. delete [] m_pKeyPassword;
  1128. m_pKeyPassword = 0;
  1129. m_ssl = 0;
  1130. t_SslLayerList *cur = m_pSslLayerList;
  1131. if (!cur)
  1132. {
  1133. m_sCriticalSection.Unlock();
  1134. return;
  1135. }
  1136. if (cur->pLayer == this)
  1137. {
  1138. m_pSslLayerList = cur->pNext;
  1139. delete cur;
  1140. }
  1141. else
  1142. while (cur->pNext)
  1143. {
  1144. if (cur->pNext->pLayer == this)
  1145. {
  1146. t_SslLayerList *tmp = cur->pNext;
  1147. cur->pNext = cur->pNext->pNext;
  1148. delete tmp;
  1149. m_sCriticalSection.Unlock();
  1150. return;
  1151. }
  1152. cur = cur->pNext;
  1153. }
  1154. if (m_sessionid != NULL)
  1155. {
  1156. SSL_SESSION_free(m_sessionid);
  1157. m_sessionid = NULL;
  1158. }
  1159. m_sessionreuse = true;
  1160. m_sCriticalSection.Unlock();
  1161. }
  1162. bool CAsyncSslSocketLayer::IsUsingSSL()
  1163. {
  1164. return m_bUseSSL;
  1165. }
  1166. BOOL CAsyncSslSocketLayer::ShutDown(int nHow /*=sends*/)
  1167. {
  1168. if (m_bUseSSL)
  1169. {
  1170. if (m_pRetrySendBuffer)
  1171. {
  1172. if (!m_nShutDown)
  1173. m_nShutDown = 1;
  1174. WSASetLastError(WSAEWOULDBLOCK);
  1175. return false;
  1176. }
  1177. #ifdef MPEXT
  1178. if (!m_bSslEstablished)
  1179. {
  1180. m_mayTriggerWriteUp = true;
  1181. SetLastError(WSAEWOULDBLOCK);
  1182. return false;
  1183. }
  1184. #endif
  1185. if (!m_nShutDown)
  1186. m_nShutDown = 1;
  1187. else
  1188. {
  1189. if (ShutDownComplete())
  1190. return ShutDownNext();
  1191. else
  1192. {
  1193. TriggerEvents();
  1194. WSASetLastError(WSAEWOULDBLOCK);
  1195. return false;
  1196. }
  1197. }
  1198. int res = pSSL_shutdown(m_ssl);
  1199. if (res != -1)
  1200. {
  1201. if (!res)
  1202. {
  1203. pSSL_shutdown(m_ssl);
  1204. }
  1205. if (ShutDownComplete())
  1206. return ShutDownNext();
  1207. else
  1208. {
  1209. TriggerEvents();
  1210. WSASetLastError(WSAEWOULDBLOCK);
  1211. return FALSE;
  1212. }
  1213. }
  1214. else
  1215. {
  1216. int error = pSSL_get_error(m_ssl, -1);
  1217. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  1218. {
  1219. #ifdef MPEXT
  1220. // retry shutdown later
  1221. m_nShutDown = 0;
  1222. #endif
  1223. TriggerEvents();
  1224. WSASetLastError(WSAEWOULDBLOCK);
  1225. return FALSE;
  1226. }
  1227. else if (ShutDownComplete())
  1228. return ShutDownNext();
  1229. else
  1230. {
  1231. TriggerEvents();
  1232. WSASetLastError(WSAEWOULDBLOCK);
  1233. return FALSE;
  1234. }
  1235. }
  1236. }
  1237. else
  1238. {
  1239. if (!m_nShutDown)
  1240. m_nShutDown = 1;
  1241. return ShutDownNext(nHow);
  1242. }
  1243. }
  1244. BOOL CAsyncSslSocketLayer::ShutDownComplete()
  1245. {
  1246. //If a ShutDown was issued, has the connection already been shut down?
  1247. if (!m_nShutDown)
  1248. return FALSE;
  1249. else if (!m_bUseSSL)
  1250. return FALSE;
  1251. else if (m_nNetworkSendBufferLen)
  1252. return FALSE;
  1253. else if (m_pRetrySendBuffer)
  1254. return FALSE;
  1255. // Empty read buffer
  1256. char buffer[1000];
  1257. int numread;
  1258. do
  1259. {
  1260. numread = pBIO_read(m_sslbio, buffer, 1000);
  1261. } while (numread > 0);
  1262. if (pBIO_ctrl_pending(m_nbio))
  1263. {
  1264. return FALSE;
  1265. }
  1266. else
  1267. {
  1268. return TRUE;
  1269. }
  1270. }
  1271. void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int ret)
  1272. {
  1273. CAsyncSslSocketLayer *pLayer = 0;
  1274. m_sCriticalSection.Lock();
  1275. t_SslLayerList *cur = m_pSslLayerList;
  1276. while (cur)
  1277. {
  1278. if (cur->pLayer->m_ssl == s)
  1279. break;
  1280. cur = cur->pNext;
  1281. }
  1282. if (!cur)
  1283. {
  1284. m_sCriticalSection.Unlock();
  1285. MessageBox(0, _T("Can't lookup SSL session!"), _T("Critical error"), MB_ICONEXCLAMATION);
  1286. return;
  1287. }
  1288. else
  1289. pLayer = cur->pLayer;
  1290. m_sCriticalSection.Unlock();
  1291. // Called while unloading?
  1292. if (!pLayer->m_bUseSSL)
  1293. return;
  1294. char * str;
  1295. int w;
  1296. w = where& ~SSL_ST_MASK;
  1297. if (w & SSL_ST_CONNECT)
  1298. {
  1299. str = "SSL_connect";
  1300. if (pLayer->m_sessionreuse)
  1301. {
  1302. SSL_SESSION * sessionid = SSL_get1_session(pLayer->m_ssl);
  1303. if (pLayer->m_sessionid != sessionid)
  1304. {
  1305. if (pLayer->m_sessionid == NULL)
  1306. {
  1307. if (SSL_session_reused(pLayer->m_ssl))
  1308. {
  1309. pLayer->LogSocketMessage(FZ_LOG_INFO, _T("Session ID reused"));
  1310. }
  1311. else
  1312. {
  1313. if ((pLayer->m_Main != NULL) && (pLayer->m_Main->m_sessionid != NULL))
  1314. {
  1315. pLayer->LogSocketMessage(FZ_LOG_INFO, _T("Main SSL session ID not reused, will not try again"));
  1316. SSL_SESSION_free(pLayer->m_Main->m_sessionid);
  1317. pLayer->m_Main->m_sessionid = NULL;
  1318. }
  1319. }
  1320. pLayer->LogSocketMessage(FZ_LOG_DEBUG, _T("Saving session ID"));
  1321. }
  1322. else
  1323. {
  1324. SSL_SESSION_free(pLayer->m_sessionid);
  1325. pLayer->LogSocketMessage(FZ_LOG_INFO, _T("Session ID changed"));
  1326. }
  1327. pLayer->m_sessionid = sessionid;
  1328. }
  1329. else
  1330. {
  1331. SSL_SESSION_free(sessionid);
  1332. }
  1333. }
  1334. }
  1335. else if (w & SSL_ST_ACCEPT)
  1336. str = "SSL_accept";
  1337. else
  1338. str = "undefined";
  1339. if (where & SSL_CB_LOOP)
  1340. {
  1341. char *buffer = new char[4096];
  1342. sprintf(buffer, "%s: %s",
  1343. str,
  1344. pSSL_state_string_long(s));
  1345. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_INFO, 0, buffer);
  1346. }
  1347. else if (where & SSL_CB_ALERT)
  1348. {
  1349. str=(where & SSL_CB_READ)? "read" : "write";
  1350. const char* desc = pSSL_alert_desc_string_long(ret);
  1351. // Don't send close notify warning
  1352. if (desc && strcmp(desc, "close notify"))
  1353. {
  1354. char *buffer = new char[4096];
  1355. sprintf(buffer, "SSL3 alert %s: %s: %s",
  1356. str,
  1357. pSSL_alert_type_string_long(ret),
  1358. desc);
  1359. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_WARNING, 0, buffer);
  1360. }
  1361. }
  1362. else if (where & SSL_CB_EXIT)
  1363. {
  1364. if (ret == 0)
  1365. {
  1366. char *buffer = new char[4096];
  1367. sprintf(buffer, "%s: failed in %s",
  1368. str,
  1369. pSSL_state_string_long(s));
  1370. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_WARNING, 0, buffer);
  1371. if (!pLayer->m_bFailureSent)
  1372. {
  1373. pLayer->m_bFailureSent=TRUE;
  1374. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1375. }
  1376. }
  1377. else if (ret < 0)
  1378. {
  1379. int error = pSSL_get_error(s,ret);
  1380. if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
  1381. {
  1382. char *buffer = new char[4096];
  1383. sprintf(buffer, "%s: error in %s",
  1384. str,
  1385. pSSL_state_string_long(s));
  1386. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_WARNING, 0, buffer);
  1387. if (!pLayer->m_bFailureSent)
  1388. {
  1389. pLayer->m_bFailureSent=TRUE;
  1390. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, pLayer->m_bSslEstablished ? SSL_FAILURE_UNKNOWN : SSL_FAILURE_ESTABLISH);
  1391. }
  1392. }
  1393. }
  1394. }
  1395. if (where & SSL_CB_HANDSHAKE_DONE)
  1396. {
  1397. int error = pSSL_get_verify_result(pLayer->m_ssl);
  1398. if (error)
  1399. {
  1400. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERIFY_CERT, error);
  1401. pLayer->m_bBlocking = TRUE;
  1402. return;
  1403. }
  1404. pLayer->m_bSslEstablished = TRUE;
  1405. pLayer->PrintSessionInfo();
  1406. pLayer->DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_ESTABLISHED);
  1407. pLayer->TriggerEvents();
  1408. }
  1409. }
  1410. void CAsyncSslSocketLayer::UnloadSSL()
  1411. {
  1412. if (!m_bSslInitialized)
  1413. return;
  1414. ResetSslSession();
  1415. m_bSslInitialized = false;
  1416. m_sCriticalSection.Lock();
  1417. m_nSslRefCount--;
  1418. if (m_nSslRefCount)
  1419. {
  1420. m_sCriticalSection.Unlock();
  1421. return;
  1422. }
  1423. #ifndef MPEXT_NO_SSLDLL
  1424. if (m_hSslDll1)
  1425. FreeLibrary(m_hSslDll1);
  1426. if (m_hSslDll2)
  1427. {
  1428. FreeLibrary(m_hSslDll2);
  1429. }
  1430. m_hSslDll1 = NULL;
  1431. m_hSslDll2 = NULL;
  1432. #endif
  1433. m_sCriticalSection.Unlock();
  1434. }
  1435. BOOL CAsyncSslSocketLayer::GetPeerCertificateData(t_SslCertData &SslCertData)
  1436. {
  1437. X509 *pX509=pSSL_get_peer_certificate(m_ssl);
  1438. if (!pX509)
  1439. return FALSE;
  1440. //Reset the contents of SslCertData
  1441. memset(&SslCertData, 0, sizeof(t_SslCertData));
  1442. //Set subject data fields
  1443. X509_NAME *pX509Name=pX509_get_subject_name(pX509);
  1444. if (pX509Name)
  1445. {
  1446. int count=pX509_NAME_entry_count(pX509Name);
  1447. for (int i=0;i<count;i++)
  1448. {
  1449. X509_NAME_ENTRY *pX509NameEntry=pX509_NAME_get_entry(pX509Name,i);
  1450. if (!pX509NameEntry)
  1451. continue;
  1452. ASN1_OBJECT *pObject = pX509_NAME_ENTRY_get_object(pX509NameEntry);
  1453. ASN1_STRING *pString = pX509_NAME_ENTRY_get_data(pX509NameEntry);
  1454. CString str;
  1455. unsigned char *out;
  1456. int len = pASN1_STRING_to_UTF8(&out, pString);
  1457. if (len > 0)
  1458. {
  1459. // Keep it huge
  1460. LPWSTR unicode = new WCHAR[len * 10];
  1461. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1462. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1463. if (unicodeLen > 0)
  1464. {
  1465. #ifdef _UNICODE
  1466. str = unicode;
  1467. #else
  1468. LPSTR ansi = new CHAR[len * 10];
  1469. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1470. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1471. if (ansiLen > 0)
  1472. str = ansi;
  1473. delete [] ansi;
  1474. #endif
  1475. }
  1476. delete [] unicode;
  1477. pCRYPTO_free(out);
  1478. }
  1479. switch(pOBJ_obj2nid(pObject))
  1480. {
  1481. case NID_organizationName:
  1482. _tcsncpy(SslCertData.subject.Organization, str, 255);
  1483. SslCertData.subject.Organization[255] = 0;
  1484. break;
  1485. case NID_organizationalUnitName:
  1486. _tcsncpy(SslCertData.subject.Unit, str, 255);
  1487. SslCertData.subject.Unit[255] = 0;
  1488. break;
  1489. case NID_commonName:
  1490. _tcsncpy(SslCertData.subject.CommonName, str, 255);
  1491. SslCertData.subject.CommonName[255] = 0;
  1492. break;
  1493. case NID_pkcs9_emailAddress:
  1494. _tcsncpy(SslCertData.subject.Mail, str, 255);
  1495. SslCertData.subject.Mail[255] = 0;
  1496. break;
  1497. case NID_countryName:
  1498. _tcsncpy(SslCertData.subject.Country, str, 255);
  1499. SslCertData.subject.Country[255] = 0;
  1500. break;
  1501. case NID_stateOrProvinceName:
  1502. _tcsncpy(SslCertData.subject.StateProvince, str, 255);
  1503. SslCertData.subject.StateProvince[255] = 0;
  1504. break;
  1505. case NID_localityName:
  1506. _tcsncpy(SslCertData.subject.Town, str, 255);
  1507. SslCertData.subject.Town[255] = 0;
  1508. break;
  1509. default:
  1510. if ( !pOBJ_nid2sn(pOBJ_obj2nid(pObject)) )
  1511. {
  1512. TCHAR tmp[20];
  1513. _stprintf(tmp, _T("%d"), pOBJ_obj2nid(pObject));
  1514. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1515. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), tmp, maxlen);
  1516. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1517. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), _T("="), maxlen);
  1518. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1519. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1520. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1521. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), _T(";"), maxlen);
  1522. }
  1523. else
  1524. {
  1525. int maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1526. USES_CONVERSION;
  1527. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), A2CT(pOBJ_nid2sn(pOBJ_obj2nid(pObject))), maxlen);
  1528. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1529. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), _T("="), maxlen);
  1530. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1531. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), str, maxlen);
  1532. maxlen = 1024 - _tcslen(SslCertData.subject.Other)-1;
  1533. _tcsncpy(SslCertData.subject.Other+_tcslen(SslCertData.subject.Other), _T(";"), maxlen);
  1534. }
  1535. break;
  1536. }
  1537. }
  1538. }
  1539. //Set issuer data fields
  1540. pX509Name=pX509_get_issuer_name(pX509);
  1541. if (pX509Name)
  1542. {
  1543. int count=pX509_NAME_entry_count(pX509Name);
  1544. for (int i=0;i<count;i++)
  1545. {
  1546. X509_NAME_ENTRY *pX509NameEntry=pX509_NAME_get_entry(pX509Name,i);
  1547. if (!pX509NameEntry)
  1548. continue;
  1549. ASN1_STRING *pString=pX509_NAME_ENTRY_get_data(pX509NameEntry);
  1550. ASN1_OBJECT *pObject=pX509_NAME_ENTRY_get_object(pX509NameEntry);
  1551. CString str;
  1552. unsigned char *out;
  1553. int len = pASN1_STRING_to_UTF8(&out, pString);
  1554. if (len > 0)
  1555. {
  1556. // Keep it huge
  1557. LPWSTR unicode = new WCHAR[len * 10];
  1558. memset(unicode, 0, sizeof(WCHAR) * len * 10);
  1559. int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, (const char *)out, len, unicode, len * 10);
  1560. if (unicodeLen > 0)
  1561. {
  1562. #ifdef _UNICODE
  1563. str = unicode;
  1564. #else
  1565. LPSTR ansi = new CHAR[len * 10];
  1566. memset(ansi, 0, sizeof(CHAR) * len * 10);
  1567. int ansiLen = WideCharToMultiByte(CP_ACP, 0, unicode, unicodeLen, ansi, len * 10, 0, 0);
  1568. if (ansiLen > 0)
  1569. str = ansi;
  1570. delete [] ansi;
  1571. #endif
  1572. }
  1573. delete [] unicode;
  1574. pCRYPTO_free(out);
  1575. }
  1576. switch(pOBJ_obj2nid(pObject))
  1577. {
  1578. case NID_organizationName:
  1579. _tcsncpy(SslCertData.issuer.Organization, str, 255);
  1580. SslCertData.issuer.Organization[255] = 0;
  1581. break;
  1582. case NID_organizationalUnitName:
  1583. _tcsncpy(SslCertData.issuer.Unit, str, 255);
  1584. SslCertData.issuer.Unit[255] = 0;
  1585. break;
  1586. case NID_commonName:
  1587. _tcsncpy(SslCertData.issuer.CommonName, str, 255);
  1588. SslCertData.issuer.CommonName[255] = 0;
  1589. break;
  1590. case NID_pkcs9_emailAddress:
  1591. _tcsncpy(SslCertData.issuer.Mail, str, 255);
  1592. SslCertData.issuer.Mail[255] = 0;
  1593. break;
  1594. case NID_countryName:
  1595. _tcsncpy(SslCertData.issuer.Country, str, 255);
  1596. SslCertData.issuer.Country[255] = 0;
  1597. break;
  1598. case NID_stateOrProvinceName:
  1599. _tcsncpy(SslCertData.issuer.StateProvince, str, 255);
  1600. SslCertData.issuer.StateProvince[255] = 0;
  1601. break;
  1602. case NID_localityName:
  1603. _tcsncpy(SslCertData.issuer.Town, str, 255);
  1604. SslCertData.issuer.Town[255] = 0;
  1605. break;
  1606. default:
  1607. if ( !pOBJ_nid2sn(pOBJ_obj2nid(pObject)) )
  1608. {
  1609. TCHAR tmp[20];
  1610. _stprintf(tmp, _T("%d"), pOBJ_obj2nid(pObject));
  1611. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1612. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), tmp, maxlen);
  1613. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1614. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), _T("="), maxlen);
  1615. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1616. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1617. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1618. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), _T(";"), maxlen);
  1619. }
  1620. else
  1621. {
  1622. int maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1623. USES_CONVERSION;
  1624. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), A2CT(pOBJ_nid2sn(pOBJ_obj2nid(pObject))), maxlen);
  1625. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1626. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), _T("="), maxlen);
  1627. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1628. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), str, maxlen);
  1629. maxlen = 1024 - _tcslen(SslCertData.issuer.Other)-1;
  1630. _tcsncpy(SslCertData.issuer.Other+_tcslen(SslCertData.issuer.Other), _T(";"), maxlen);
  1631. }
  1632. break;
  1633. }
  1634. }
  1635. }
  1636. //Set date fields
  1637. static const char *mon[12]=
  1638. {
  1639. "Jan","Feb","Mar","Apr","May","Jun",
  1640. "Jul","Aug","Sep","Oct","Nov","Dec"
  1641. };
  1642. //Valid from
  1643. ASN1_UTCTIME *pTime=X509_get_notBefore(pX509);
  1644. if (!pTime)
  1645. {
  1646. pX509_free(pX509);
  1647. return FALSE;
  1648. }
  1649. char *v;
  1650. int gmt = 0;
  1651. int i;
  1652. int y=0, M=0, d=0, h=0, m=0, s=0;
  1653. i = pTime->length;
  1654. v = (char *)pTime->data;
  1655. if (i < 10)
  1656. {
  1657. pX509_free(pX509);
  1658. return FALSE;
  1659. }
  1660. if (v[i-1] == 'Z') gmt=1;
  1661. for (i=0; i<10; i++)
  1662. if ((v[i] > '9') || (v[i] < '0'))
  1663. {
  1664. pX509_free(pX509);
  1665. return FALSE;
  1666. }
  1667. y= (v[0]-'0')*10+(v[1]-'0');
  1668. if (y < 50) y+=100;
  1669. M= (v[2]-'0')*10+(v[3]-'0');
  1670. if ((M > 12) || (M < 1))
  1671. {
  1672. pX509_free(pX509);
  1673. return FALSE;
  1674. }
  1675. d= (v[4]-'0')*10+(v[5]-'0');
  1676. h= (v[6]-'0')*10+(v[7]-'0');
  1677. m= (v[8]-'0')*10+(v[9]-'0');
  1678. if ( (v[10] >= '0') && (v[10] <= '9') &&
  1679. (v[11] >= '0') && (v[11] <= '9'))
  1680. s= (v[10]-'0')*10+(v[11]-'0');
  1681. SslCertData.validFrom.y = y+1900;
  1682. SslCertData.validFrom.M = M;
  1683. SslCertData.validFrom.d = d;
  1684. SslCertData.validFrom.h = h;
  1685. SslCertData.validFrom.m = m;
  1686. SslCertData.validFrom.s = s;
  1687. //Valid until
  1688. pTime = X509_get_notAfter(pX509);
  1689. if (!pTime)
  1690. {
  1691. pX509_free(pX509);
  1692. return FALSE;
  1693. }
  1694. gmt = 0;
  1695. i;
  1696. y=0,M=0,d=0,h=0,m=0,s=0;
  1697. i=pTime->length;
  1698. v=(char *)pTime->data;
  1699. if (i < 10)
  1700. {
  1701. pX509_free(pX509);
  1702. return FALSE;
  1703. }
  1704. if (v[i-1] == 'Z') gmt=1;
  1705. for (i=0; i<10; i++)
  1706. if ((v[i] > '9') || (v[i] < '0'))
  1707. {
  1708. pX509_free(pX509);
  1709. return FALSE;
  1710. }
  1711. y= (v[0]-'0')*10+(v[1]-'0');
  1712. if (y < 50) y+=100;
  1713. M= (v[2]-'0')*10+(v[3]-'0');
  1714. if ((M > 12) || (M < 1))
  1715. {
  1716. pX509_free(pX509);
  1717. return FALSE;
  1718. }
  1719. d= (v[4]-'0')*10+(v[5]-'0');
  1720. h= (v[6]-'0')*10+(v[7]-'0');
  1721. m= (v[8]-'0')*10+(v[9]-'0');
  1722. if ( (v[10] >= '0') && (v[10] <= '9') &&
  1723. (v[11] >= '0') && (v[11] <= '9'))
  1724. s= (v[10]-'0')*10+(v[11]-'0');
  1725. SslCertData.validUntil.y = y+1900;
  1726. SslCertData.validUntil.M = M;
  1727. SslCertData.validUntil.d = d;
  1728. SslCertData.validUntil.h = h;
  1729. SslCertData.validUntil.m = m;
  1730. SslCertData.validUntil.s = s;
  1731. unsigned int length = 20;
  1732. pX509_digest(pX509, pEVP_sha1(), SslCertData.hash, &length);
  1733. SslCertData.priv_data = m_nSslAsyncNotifyId;
  1734. pX509_free(pX509);
  1735. SslCertData.verificationResult = m_nVerificationResult;
  1736. SslCertData.verificationDepth = m_nVerificationDepth;
  1737. return TRUE;
  1738. }
  1739. void CAsyncSslSocketLayer::SetNotifyReply(int nID, int nCode, int result)
  1740. {
  1741. if (!m_bBlocking)
  1742. return;
  1743. if (nID != m_nSslAsyncNotifyId)
  1744. return;
  1745. if (nCode != SSL_VERIFY_CERT)
  1746. return;
  1747. m_bBlocking = FALSE;
  1748. if (!result)
  1749. {
  1750. m_nNetworkError = WSAECONNABORTED;
  1751. WSASetLastError(WSAECONNABORTED);
  1752. if (!m_bFailureSent)
  1753. {
  1754. m_bFailureSent = TRUE;
  1755. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_FAILURE, SSL_FAILURE_CERTREJECTED);
  1756. }
  1757. TriggerEvent(FD_CLOSE, 0, TRUE);
  1758. return;
  1759. }
  1760. m_bSslEstablished = TRUE;
  1761. PrintSessionInfo();
  1762. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_INFO, SSL_INFO_ESTABLISHED);
  1763. TriggerEvents();
  1764. }
  1765. void CAsyncSslSocketLayer::PrintSessionInfo()
  1766. {
  1767. #ifdef MPEXT
  1768. const
  1769. #endif
  1770. SSL_CIPHER *ciph;
  1771. X509 *cert;
  1772. ciph = pSSL_get_current_cipher(m_ssl);
  1773. char enc[4096] = {0};
  1774. cert=pSSL_get_peer_certificate(m_ssl);
  1775. if (cert != NULL)
  1776. {
  1777. EVP_PKEY *pkey = pX509_get_pubkey(cert);
  1778. if (pkey != NULL)
  1779. {
  1780. if (0)
  1781. ;
  1782. #ifndef NO_RSA
  1783. else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
  1784. && pkey->pkey.rsa->n != NULL)
  1785. sprintf(enc, "%d bit RSA", pBN_num_bits(pkey->pkey.rsa->n));
  1786. #endif
  1787. #ifndef NO_DSA
  1788. else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
  1789. && pkey->pkey.dsa->p != NULL)
  1790. sprintf(enc, "%d bit DSA", pBN_num_bits(pkey->pkey.dsa->p));
  1791. #endif
  1792. pEVP_PKEY_free(pkey);
  1793. }
  1794. pX509_free(cert);
  1795. /* The SSL API does not allow us to look at temporary RSA/DH keys,
  1796. * otherwise we should print their lengths too */
  1797. }
  1798. char *buffer = new char[4096];
  1799. sprintf(buffer, "Using %s, cipher %s: %s, %s",
  1800. pSSL_get_version(m_ssl),
  1801. pSSL_CIPHER_get_version(ciph),
  1802. pSSL_CIPHER_get_name(ciph),
  1803. enc);
  1804. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_INFO, 0, buffer);
  1805. }
  1806. void CAsyncSslSocketLayer::OnConnect(int nErrorCode)
  1807. {
  1808. if (m_bUseSSL && nErrorCode)
  1809. TriggerEvent(FD_WRITE, 0);
  1810. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  1811. }
  1812. int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1813. {
  1814. X509 *err_cert;
  1815. int err, depth;
  1816. SSL *ssl;
  1817. err_cert = pX509_STORE_CTX_get_current_cert(ctx);
  1818. err = pX509_STORE_CTX_get_error(ctx);
  1819. depth = pX509_STORE_CTX_get_error_depth(ctx);
  1820. /*
  1821. * Retrieve the pointer to the SSL of the connection currently treated
  1822. * and the application specific data stored into the SSL object.
  1823. */
  1824. ssl = (SSL *)pX509_STORE_CTX_get_ex_data(ctx, pSSL_get_ex_data_X509_STORE_CTX_idx());
  1825. // Lookup CAsyncSslSocketLayer instance
  1826. CAsyncSslSocketLayer *pLayer = 0;
  1827. m_sCriticalSection.Lock();
  1828. t_SslLayerList *cur = m_pSslLayerList;
  1829. while (cur)
  1830. {
  1831. if (cur->pLayer->m_ssl == ssl)
  1832. break;
  1833. cur = cur->pNext;
  1834. }
  1835. if (!cur)
  1836. {
  1837. m_sCriticalSection.Unlock();
  1838. MessageBox(0, _T("Can't lookup SSL session!"), _T("Critical error"), MB_ICONEXCLAMATION);
  1839. return 1;
  1840. }
  1841. else
  1842. pLayer = cur->pLayer;
  1843. m_sCriticalSection.Unlock();
  1844. /*
  1845. * Catch a too long certificate chain. The depth limit set using
  1846. * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
  1847. * that whenever the "depth>verify_depth" condition is met, we
  1848. * have violated the limit and want to log this error condition.
  1849. * We must do it here, because the CHAIN_TOO_LONG error would not
  1850. * be found explicitly; only errors introduced by cutting off the
  1851. * additional certificates would be logged.
  1852. */
  1853. if (depth > 10) {//mydata->verify_depth) {
  1854. preverify_ok = 0;
  1855. err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  1856. pX509_STORE_CTX_set_error(ctx, err);
  1857. }
  1858. if (!preverify_ok)
  1859. {
  1860. if (!pLayer->m_nVerificationResult)
  1861. {
  1862. pLayer->m_nVerificationDepth = depth;
  1863. pLayer->m_nVerificationResult = err;
  1864. }
  1865. }
  1866. return 1;
  1867. }
  1868. BOOL CAsyncSslSocketLayer::SetCertStorage(CString file)
  1869. {
  1870. m_CertStorage = file;
  1871. return TRUE;
  1872. }
  1873. void CAsyncSslSocketLayer::OnClose(int nErrorCode)
  1874. {
  1875. m_onCloseCalled = true;
  1876. if (m_bUseSSL && pBIO_ctrl)
  1877. {
  1878. if (pBIO_ctrl(m_sslbio, BIO_CTRL_PENDING, 0, NULL) > 0)
  1879. {
  1880. TriggerEvents();
  1881. }
  1882. else TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1883. }
  1884. else
  1885. TriggerEvent(FD_CLOSE, nErrorCode, TRUE);
  1886. }
  1887. void CAsyncSslSocketLayer::PrintLastErrorMsg()
  1888. {
  1889. int err = pERR_get_error();
  1890. while (err)
  1891. {
  1892. char *buffer = new char[512];
  1893. pERR_error_string(err, buffer);
  1894. err = pERR_get_error();
  1895. DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, SSL_VERBOSE_WARNING, 0, buffer);
  1896. }
  1897. }
  1898. bool CAsyncSslSocketLayer::CreateSslCertificate(LPCTSTR filename, int bits, unsigned char* country, unsigned char* state,
  1899. unsigned char* locality, unsigned char* organization, unsigned char* unit, unsigned char* cname,
  1900. unsigned char *email, CString& err)
  1901. {
  1902. // Certificate valid for a year
  1903. int days = 365;
  1904. CAsyncSslSocketLayer layer;
  1905. if (layer.InitSSL())
  1906. {
  1907. err = _T("Failed to initialize SSL library");
  1908. return false;
  1909. }
  1910. X509 *x;
  1911. EVP_PKEY *pk;
  1912. RSA *rsa;
  1913. X509_NAME *name = NULL;
  1914. if ((pk = pEVP_PKEY_new()) == NULL)
  1915. {
  1916. err = _T("Could not create key object");
  1917. return false;
  1918. }
  1919. if ((x = pX509_new()) == NULL)
  1920. {
  1921. err = _T("Could not create certificate object");
  1922. return false;
  1923. }
  1924. rsa = pRSA_generate_key(bits, RSA_F4, 0/*callback*/, NULL);
  1925. if (!pEVP_PKEY_assign(pk, EVP_PKEY_RSA, (char *)(rsa)))
  1926. {
  1927. err = _T("Failed to assign rsa key to key object");
  1928. return false;
  1929. }
  1930. rsa = NULL;
  1931. pX509_set_version(x,2);
  1932. pASN1_INTEGER_set(pX509_get_serialNumber(x), 0/*serial*/);
  1933. pX509_gmtime_adj(X509_get_notBefore(x),0);
  1934. pX509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);
  1935. pX509_set_pubkey(x,pk);
  1936. name = pX509_get_subject_name(x);
  1937. /* This function creates and adds the entry, working out the
  1938. * correct string type and performing checks on its length.
  1939. * Normally we'd check the return value for errors...
  1940. */
  1941. pX509_NAME_add_entry_by_txt(name, "CN",
  1942. MBSTRING_ASC, cname, -1, -1, 0);
  1943. pX509_NAME_add_entry_by_txt(name, "C",
  1944. MBSTRING_ASC, country, -1, -1, 0);
  1945. pX509_NAME_add_entry_by_txt(name, "ST",
  1946. MBSTRING_ASC, state, -1, -1, 0);
  1947. pX509_NAME_add_entry_by_txt(name, "L",
  1948. MBSTRING_ASC, locality, -1, -1, 0);
  1949. pX509_NAME_add_entry_by_txt(name, "O",
  1950. MBSTRING_ASC, organization, -1, -1, 0);
  1951. pX509_NAME_add_entry_by_txt(name, "OU",
  1952. MBSTRING_ASC, unit, -1, -1, 0);
  1953. pX509_NAME_add_entry_by_NID(name, NID_pkcs9_emailAddress,
  1954. MBSTRING_ASC, email, -1, -1, 0);
  1955. /* Its self signed so set the issuer name to be the same as the
  1956. * subject.
  1957. */
  1958. pX509_set_issuer_name(x,name);
  1959. if (!pX509_sign(x, pk, pEVP_sha1()))
  1960. {
  1961. err = _T("Failed to sign certificate");
  1962. return false;
  1963. }
  1964. // Write key and certificate to file
  1965. // We use a memory bio, since the OpenSSL functions accepting a filepointer
  1966. // do crash for no obvious reason.
  1967. #ifndef _UNICODE
  1968. FILE* file = fopen(filename, "w+");
  1969. #else
  1970. FILE* file = _wfopen(filename, _T("w+"));
  1971. #endif
  1972. if (!file)
  1973. {
  1974. err = _T("Failed to open output file");
  1975. return false;
  1976. }
  1977. BIO* bio = pBIO_new(pBIO_s_mem());
  1978. #ifdef MPEXT
  1979. pPEM_ASN1_write_bio((i2d_of_void*)pi2d_PrivateKey, (((pk)->type == EVP_PKEY_DSA)?PEM_STRING_DSA:PEM_STRING_RSA), bio, (char *)pk, NULL, NULL, 0, NULL, NULL);
  1980. pPEM_ASN1_write_bio((i2d_of_void*)pi2d_X509, PEM_STRING_X509, bio, (char *)x, NULL, NULL, 0, NULL, NULL);
  1981. #else
  1982. pPEM_ASN1_write_bio((int (*)())pi2d_PrivateKey, (((pk)->type == EVP_PKEY_DSA)?PEM_STRING_DSA:PEM_STRING_RSA), bio, (char *)pk, NULL, NULL, 0, NULL, NULL);
  1983. pPEM_ASN1_write_bio((int (*)())pi2d_X509, PEM_STRING_X509, bio, (char *)x, NULL, NULL, 0, NULL, NULL);
  1984. #endif
  1985. char buffer[1001];
  1986. int len;
  1987. while ((len = pBIO_read(bio, buffer, 1000)) > 0)
  1988. {
  1989. buffer[len] = 0;
  1990. fprintf(file, buffer);
  1991. }
  1992. fclose(file);
  1993. pX509_free(x);
  1994. pEVP_PKEY_free(pk);
  1995. pBIO_free(bio);
  1996. layer.UnloadSSL();
  1997. return true;
  1998. }
  1999. int CAsyncSslSocketLayer::SetCertKeyFile(const char* cert, const char* key, const char* pass, CString* error /*=0*/)
  2000. {
  2001. int res = InitSSL();
  2002. if (res)
  2003. return res;
  2004. m_sCriticalSection.Lock();
  2005. if (!m_ssl_ctx)
  2006. {
  2007. // Create new context
  2008. if (!(m_ssl_ctx = pSSL_CTX_new( pSSLv23_method())))
  2009. {
  2010. m_sCriticalSection.Unlock();
  2011. return SSL_FAILURE_INITSSL;
  2012. }
  2013. m_contextRefCount[m_ssl_ctx] = 1;
  2014. }
  2015. pSSL_CTX_set_default_passwd_cb(m_ssl_ctx, pem_passwd_cb);
  2016. pSSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
  2017. if (pass)
  2018. {
  2019. size_t len = strlen(pass);
  2020. m_pKeyPassword = new char[len + 1];
  2021. strcpy(m_pKeyPassword, pass);
  2022. }
  2023. else
  2024. {
  2025. delete [] m_pKeyPassword;
  2026. m_pKeyPassword = 0;
  2027. }
  2028. if (pSSL_CTX_use_certificate_chain_file(m_ssl_ctx, cert) <= 0)
  2029. //if (pSSL_CTX_use_certificate_file(m_ssl_ctx, cert, SSL_FILETYPE_PEM) <= 0)
  2030. {
  2031. if (error)
  2032. *error = _T("Could not load certificate file.");
  2033. m_sCriticalSection.Unlock();
  2034. return SSL_FAILURE_VERIFYCERT;
  2035. }
  2036. if (pSSL_CTX_use_PrivateKey_file(m_ssl_ctx, key, SSL_FILETYPE_PEM) <= 0)
  2037. {
  2038. if (error)
  2039. *error = _T("Could not load key file.");
  2040. m_sCriticalSection.Unlock();
  2041. return SSL_FAILURE_VERIFYCERT;
  2042. }
  2043. if (!pSSL_CTX_check_private_key(m_ssl_ctx))
  2044. {
  2045. if (error)
  2046. *error = _T("Private key does not match the certificate public key.");
  2047. m_sCriticalSection.Unlock();
  2048. return SSL_FAILURE_VERIFYCERT;
  2049. }
  2050. m_sCriticalSection.Unlock();
  2051. return 0;
  2052. }
  2053. int CAsyncSslSocketLayer::SendRaw(const void* lpBuf, int nBufLen, int nFlags)
  2054. {
  2055. if (!m_bUseSSL)
  2056. {
  2057. SetLastError(WSANOTINITIALISED);
  2058. return SOCKET_ERROR;
  2059. }
  2060. if (!lpBuf)
  2061. return 0;
  2062. if (m_nNetworkError)
  2063. {
  2064. SetLastError(m_nNetworkError);
  2065. return SOCKET_ERROR;
  2066. }
  2067. if (m_nShutDown)
  2068. {
  2069. SetLastError(WSAESHUTDOWN);
  2070. return SOCKET_ERROR;
  2071. }
  2072. if (m_nNetworkSendBufferLen)
  2073. {
  2074. SetLastError(WSAEINPROGRESS);
  2075. return SOCKET_ERROR;
  2076. }
  2077. if (!nBufLen)
  2078. return 0;
  2079. if (m_nNetworkSendBufferMaxLen < nBufLen)
  2080. m_nNetworkSendBufferMaxLen = nBufLen;
  2081. delete [] m_pNetworkSendBuffer;
  2082. m_pNetworkSendBuffer = new char[m_nNetworkSendBufferMaxLen];
  2083. memcpy(m_pNetworkSendBuffer, lpBuf, nBufLen);
  2084. m_nNetworkSendBufferLen = nBufLen;
  2085. TriggerEvent(FD_WRITE, 0);
  2086. return nBufLen;
  2087. }
  2088. void CAsyncSslSocketLayer::TriggerEvents()
  2089. {
  2090. if (pBIO_ctrl_pending(m_nbio) > 0)
  2091. {
  2092. if (m_mayTriggerWrite)
  2093. {
  2094. m_mayTriggerWrite = false;
  2095. TriggerEvent(FD_WRITE, 0);
  2096. }
  2097. }
  2098. else if (!m_nNetworkSendBufferLen && m_bSslEstablished && !m_pRetrySendBuffer)
  2099. {
  2100. if (pBIO_ctrl_get_write_guarantee(m_sslbio) > 0 && m_mayTriggerWriteUp)
  2101. {
  2102. m_mayTriggerWriteUp = false;
  2103. TriggerEvent(FD_WRITE, 0, TRUE);
  2104. }
  2105. }
  2106. if (m_bSslEstablished && pBIO_ctrl_pending(m_sslbio) > 0)
  2107. {
  2108. if (m_mayTriggerReadUp && !m_bBlocking)
  2109. {
  2110. m_mayTriggerReadUp = false;
  2111. TriggerEvent(FD_READ, 0, TRUE);
  2112. }
  2113. }
  2114. else
  2115. {
  2116. if (pBIO_ctrl_get_write_guarantee(m_nbio) > 0 && m_mayTriggerRead)
  2117. {
  2118. m_mayTriggerRead = false;
  2119. TriggerEvent(FD_READ, 0);
  2120. }
  2121. }
  2122. if (m_onCloseCalled && m_bSslEstablished)
  2123. {
  2124. if (pBIO_ctrl_pending(m_sslbio) <= 0)
  2125. TriggerEvent(FD_CLOSE, 0, TRUE);
  2126. }
  2127. }
  2128. int CAsyncSslSocketLayer::pem_passwd_cb(char *buf, int size, int rwflag, void *userdata)
  2129. {
  2130. CAsyncSslSocketLayer* pThis = (CAsyncSslSocketLayer*)userdata;
  2131. if (!pThis || !pThis->m_pKeyPassword)
  2132. return 0;
  2133. int len = strlen(pThis->m_pKeyPassword);
  2134. if (len >= size)
  2135. len = size - 1;
  2136. memcpy(buf, pThis->m_pKeyPassword, len);
  2137. buf[len] = 0;
  2138. return len;
  2139. }