AsyncSslSocketLayer.cpp 60 KB

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