SSLHelper.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Author : Bruce Liang
  5. * Website : https://github.com/ldcsaa
  6. * Project : https://github.com/ldcsaa/HP-Socket
  7. * Blog : http://www.cnblogs.com/ldcsaa
  8. * Wiki : http://www.oschina.net/p/hp-socket
  9. * QQ Group : 44636872, 75375912
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. #include "SSLHelper.h"
  24. #ifdef _SSL_SUPPORT
  25. #include "SocketHelper.h"
  26. #include "common/FileHelper.h"
  27. #include "openssl/ssl.h"
  28. #include "openssl/err.h"
  29. #include "openssl/engine.h"
  30. #include "openssl/x509v3.h"
  31. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  32. int CSSLInitializer::sm_iLockNum = 0;
  33. CSimpleRWLock* CSSLInitializer::sm_pcsLocks = nullptr;
  34. #endif
  35. CSSLInitializer CSSLInitializer::sm_instance;
  36. const DWORD CSSLSessionPool::DEFAULT_ITEM_CAPACITY = CItemPool::DEFAULT_ITEM_CAPACITY;
  37. const DWORD CSSLSessionPool::DEFAULT_ITEM_POOL_SIZE = CItemPool::DEFAULT_POOL_SIZE;
  38. const DWORD CSSLSessionPool::DEFAULT_ITEM_POOL_HOLD = CItemPool::DEFAULT_POOL_HOLD;
  39. const DWORD CSSLSessionPool::DEFAULT_SESSION_LOCK_TIME = DEFAULT_OBJECT_CACHE_LOCK_TIME;
  40. const DWORD CSSLSessionPool::DEFAULT_SESSION_POOL_SIZE = DEFAULT_OBJECT_CACHE_POOL_SIZE;
  41. const DWORD CSSLSessionPool::DEFAULT_SESSION_POOL_HOLD = DEFAULT_OBJECT_CACHE_POOL_HOLD;
  42. CSSLInitializer::CSSLInitializer()
  43. {
  44. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  45. sm_iLockNum = CRYPTO_num_locks();
  46. if(sm_iLockNum > 0)
  47. sm_pcsLocks = new CSimpleRWLock[sm_iLockNum];
  48. /*
  49. #ifdef _DEBUG
  50. CRYPTO_malloc_debug_init();
  51. CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
  52. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
  53. #endif
  54. */
  55. CRYPTO_set_locking_callback (&ssl_lock_callback);
  56. CRYPTO_set_dynlock_create_callback (&ssl_lock_dyn_create_callback);
  57. CRYPTO_set_dynlock_destroy_callback (&ssl_lock_dyn_destroy_callback);
  58. CRYPTO_set_dynlock_lock_callback (&ssl_lock_dyn_callback);
  59. SSL_library_init();
  60. SSL_load_error_strings();
  61. OpenSSL_add_all_algorithms();
  62. #else
  63. OPENSSL_init_ssl(OPENSSL_INIT_SSL_DEFAULT, nullptr);
  64. #endif
  65. }
  66. CSSLInitializer::~CSSLInitializer()
  67. {
  68. CleanupThreadState();
  69. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  70. CONF_modules_free();
  71. ENGINE_cleanup();
  72. EVP_cleanup();
  73. CRYPTO_cleanup_all_ex_data();
  74. ERR_free_strings();
  75. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_1_0_2
  76. SSL_COMP_free_compression_methods();
  77. #endif
  78. CRYPTO_set_locking_callback (nullptr);
  79. CRYPTO_set_dynlock_create_callback (nullptr);
  80. CRYPTO_set_dynlock_destroy_callback (nullptr);
  81. CRYPTO_set_dynlock_lock_callback (nullptr);
  82. if(sm_iLockNum > 0)
  83. {
  84. delete[] sm_pcsLocks;
  85. sm_pcsLocks = nullptr;
  86. sm_iLockNum = 0;
  87. }
  88. #endif
  89. }
  90. void CSSLInitializer::CleanupThreadState(THR_ID dwThreadID)
  91. {
  92. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  93. CRYPTO_THREADID tid = {nullptr, dwThreadID};
  94. CRYPTO_THREADID_current(&tid);
  95. ERR_remove_thread_state(&tid);
  96. #else
  97. OPENSSL_thread_stop();
  98. #endif
  99. }
  100. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  101. void CSSLInitializer::ssl_lock_callback(int mode, int n, const char *file, int line)
  102. {
  103. mode & CRYPTO_LOCK
  104. ? (mode & CRYPTO_READ
  105. ? sm_pcsLocks[n].lock_shared()
  106. : sm_pcsLocks[n].lock())
  107. : (mode & CRYPTO_READ
  108. ? sm_pcsLocks[n].unlock_shared()
  109. : sm_pcsLocks[n].unlock());
  110. }
  111. CRYPTO_dynlock_value* CSSLInitializer::ssl_lock_dyn_create_callback(const char *file, int line)
  112. {
  113. return new DynamicLock;
  114. }
  115. void CSSLInitializer::ssl_lock_dyn_callback(int mode, CRYPTO_dynlock_value* l, const char *file, int line)
  116. {
  117. mode & CRYPTO_LOCK
  118. ? (mode & CRYPTO_READ
  119. ? l->cs.lock_shared()
  120. : l->cs.lock())
  121. : (mode & CRYPTO_READ
  122. ? l->cs.unlock_shared()
  123. : l->cs.unlock());
  124. }
  125. void CSSLInitializer::ssl_lock_dyn_destroy_callback(CRYPTO_dynlock_value* l, const char *file, int line)
  126. {
  127. delete l;
  128. }
  129. #endif
  130. BOOL CSSLContext::Initialize(EnSSLSessionMode enSessionMode, int iVerifyMode, BOOL bMemory, LPVOID lpPemCert, LPVOID lpPemKey, LPVOID lpKeyPasswod, LPVOID lpCAPemCert, HP_Fn_SNI_ServerNameCallback fnServerNameCallback)
  131. {
  132. ASSERT(!IsValid());
  133. if(IsValid())
  134. {
  135. ::SetLastError(ERROR_INVALID_STATE);
  136. return FALSE;
  137. }
  138. m_enSessionMode = enSessionMode;
  139. if(AddContext(iVerifyMode, bMemory, lpPemCert, lpPemKey, lpKeyPasswod, lpCAPemCert) == 0)
  140. m_sslCtx = GetContext(0);
  141. else
  142. {
  143. EXECUTE_RESTORE_ERROR(Cleanup());
  144. return FALSE;
  145. }
  146. SetServerNameCallback(fnServerNameCallback);
  147. return TRUE;
  148. }
  149. int CSSLContext::AddServerContext(int iVerifyMode, BOOL bMemory, LPVOID lpPemCert, LPVOID lpPemKey, LPVOID lpKeyPasswod, LPVOID lpCAPemCert)
  150. {
  151. ASSERT(IsValid());
  152. if(!IsValid())
  153. {
  154. ::SetLastError(ERROR_INVALID_STATE);
  155. return FALSE;
  156. }
  157. if(m_enSessionMode != SSL_SM_SERVER)
  158. {
  159. ::SetLastError(ERROR_INVALID_OPERATION);
  160. return FALSE;
  161. }
  162. return AddContext(iVerifyMode, bMemory, lpPemCert, lpPemKey, lpKeyPasswod, lpCAPemCert);
  163. }
  164. BOOL CSSLContext::BindServerName(LPCTSTR lpszServerName, int iContextIndex)
  165. {
  166. ASSERT(lpszServerName && iContextIndex >= 0 && !::IsIPAddress(lpszServerName));
  167. if(!lpszServerName || iContextIndex < 0 || ::IsIPAddress(lpszServerName))
  168. {
  169. ::SetLastError(ERROR_INVALID_PARAMETER);
  170. return FALSE;
  171. }
  172. int iLen = lstrlen(lpszServerName);
  173. LPCTSTR lpszSep = ::StrChr(lpszServerName, SSL_DOMAIN_SEP_CHAR);
  174. if(lpszSep == nullptr || lpszSep == lpszServerName || lpszSep == (lpszServerName + iLen - 1))
  175. {
  176. ::SetLastError(ERROR_INVALID_PARAMETER);
  177. return FALSE;
  178. }
  179. int iSize = (int)m_lsSslCtxs.size();
  180. if(iSize <= iContextIndex)
  181. {
  182. ::SetLastError(ERROR_INVALID_INDEX);
  183. return FALSE;
  184. }
  185. m_sslServerNames[lpszServerName] = iContextIndex;
  186. return TRUE;
  187. }
  188. int CSSLContext::AddContext(int iVerifyMode, BOOL bMemory, LPVOID lpPemCert, LPVOID lpPemKey, LPVOID lpKeyPasswod, LPVOID lpCAPemCert)
  189. {
  190. USES_CONVERSION;
  191. int iIndex = -1;
  192. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_1_1_0
  193. SSL_CTX* sslCtx = SSL_CTX_new(SSLv23_method());
  194. #else
  195. SSL_CTX* sslCtx = SSL_CTX_new(TLS_method());
  196. #endif
  197. SSL_CTX_set_quiet_shutdown(sslCtx, 1);
  198. SSL_CTX_set_verify(sslCtx, iVerifyMode, nullptr);
  199. if(!SSL_CTX_set_cipher_list(sslCtx, T2CA(m_strCipherList)))
  200. ::SetLastError(ERROR_EMPTY);
  201. else
  202. {
  203. if(m_enSessionMode == SSL_SM_SERVER)
  204. {
  205. static volatile ULONG s_session_id_context = 0;
  206. ULONG session_id_context = ::InterlockedIncrement(&s_session_id_context);
  207. SSL_CTX_set_session_id_context(sslCtx, (BYTE*)&session_id_context, sizeof(session_id_context));
  208. }
  209. if(LoadCertAndKey(sslCtx, iVerifyMode, bMemory, lpPemCert, lpPemKey, lpKeyPasswod, lpCAPemCert))
  210. {
  211. iIndex = (int)m_lsSslCtxs.size();
  212. m_lsSslCtxs.push_back(sslCtx);
  213. }
  214. }
  215. if(iIndex < 0)
  216. EXECUTE_RESTORE_ERROR(SSL_CTX_free(sslCtx));
  217. return iIndex;
  218. }
  219. BOOL CSSLContext::LoadCertAndKey(SSL_CTX* sslCtx, int iVerifyMode, BOOL bMemory, LPVOID lpPemCert, LPVOID lpPemKey, LPVOID lpKeyPasswod, LPVOID lpCAPemCert)
  220. {
  221. if(bMemory)
  222. return LoadCertAndKeyByMemory(sslCtx, iVerifyMode, (LPCSTR)lpPemCert, (LPCSTR)lpPemKey, (LPCSTR)lpKeyPasswod, (LPCSTR)lpCAPemCert);
  223. else
  224. return LoadCertAndKeyByFile(sslCtx, iVerifyMode, (LPCTSTR)lpPemCert, (LPCTSTR)lpPemKey, (LPCTSTR)lpKeyPasswod, (LPCTSTR)lpCAPemCert);
  225. }
  226. BOOL CSSLContext::LoadCertAndKeyByFile(SSL_CTX* sslCtx, int iVerifyMode, LPCTSTR lpszPemCertFile, LPCTSTR lpszPemKeyFile, LPCTSTR lpszKeyPassword, LPCTSTR lpszCAPemCertFileOrPath)
  227. {
  228. USES_CONVERSION;
  229. if(::IsStrNotEmpty(lpszCAPemCertFileOrPath))
  230. {
  231. LPCTSTR lpszCAPemCertFile = nullptr;
  232. LPCTSTR lpszCAPemCertPath = nullptr;
  233. CFile fCAPemCertFile(lpszCAPemCertFileOrPath, O_RDONLY | O_CLOEXEC);
  234. if(!fCAPemCertFile.IsExist())
  235. {
  236. ::SetLastError(ERROR_FILE_NOT_FOUND);
  237. return FALSE;
  238. }
  239. if(fCAPemCertFile.IsFile())
  240. lpszCAPemCertFile = lpszCAPemCertFileOrPath;
  241. else if(fCAPemCertFile.IsDirectory())
  242. lpszCAPemCertPath = lpszCAPemCertFileOrPath;
  243. else
  244. {
  245. ::SetLastError(ERROR_BAD_FILE_TYPE);
  246. return FALSE;
  247. }
  248. if(!SSL_CTX_load_verify_locations(sslCtx, T2CA(lpszCAPemCertFile), T2CA(lpszCAPemCertPath)))
  249. {
  250. ::SetLastError(ERROR_INVALID_DATA);
  251. return FALSE;
  252. }
  253. if(!SSL_CTX_set_default_verify_paths(sslCtx))
  254. {
  255. ::SetLastError(ERROR_FUNCTION_FAILED);
  256. return FALSE;
  257. }
  258. if(m_enSessionMode == SSL_SM_SERVER && (iVerifyMode & SSL_VM_PEER) && lpszCAPemCertFile != nullptr)
  259. {
  260. STACK_OF(X509_NAME)* caCertNames = SSL_load_client_CA_file(T2CA(lpszCAPemCertFile));
  261. if(caCertNames == nullptr)
  262. {
  263. ::SetLastError(ERROR_EMPTY);
  264. return FALSE;
  265. }
  266. SSL_CTX_set_client_CA_list(sslCtx, caCertNames);
  267. }
  268. }
  269. if(::IsStrNotEmpty(lpszPemCertFile))
  270. {
  271. CFile fPemCertFile(lpszPemCertFile, O_RDONLY | O_CLOEXEC);
  272. if(!fPemCertFile.IsFile())
  273. {
  274. ::SetLastError(ERROR_FILE_NOT_FOUND);
  275. return FALSE;
  276. }
  277. if(::IsStrEmpty(lpszPemKeyFile))
  278. {
  279. ::SetLastError(ERROR_INVALID_PARAMETER);
  280. return FALSE;
  281. }
  282. CFile fPemKeyFile(lpszPemKeyFile, O_RDONLY | O_CLOEXEC);
  283. if(!fPemKeyFile.IsFile())
  284. {
  285. ::SetLastError(ERROR_FILE_NOT_FOUND);
  286. return FALSE;
  287. }
  288. if(::IsStrNotEmpty(lpszKeyPassword))
  289. SSL_CTX_set_default_passwd_cb_userdata(sslCtx, (void*)T2CA(lpszKeyPassword));
  290. if(!SSL_CTX_use_PrivateKey_file(sslCtx, T2CA(lpszPemKeyFile), SSL_FILETYPE_PEM))
  291. {
  292. ::SetLastError(ERROR_INVALID_PASSWORD);
  293. return FALSE;
  294. }
  295. if(!SSL_CTX_use_certificate_chain_file(sslCtx, T2CA(lpszPemCertFile)))
  296. {
  297. ::SetLastError(ERROR_INVALID_DATA);
  298. return FALSE;
  299. }
  300. if(!SSL_CTX_check_private_key(sslCtx))
  301. {
  302. ::SetLastError(ERROR_INVALID_ACCESS);
  303. return FALSE;
  304. }
  305. }
  306. return TRUE;
  307. }
  308. BOOL CSSLContext::LoadCertAndKeyByMemory(SSL_CTX* sslCtx, int iVerifyMode, LPCSTR lpszPemCert, LPCSTR lpszPemKey, LPCSTR lpszKeyPassword, LPCSTR lpszCAPemCert)
  309. {
  310. if(!LoadCAPemCertByMemory(sslCtx, iVerifyMode, lpszCAPemCert))
  311. return FALSE;
  312. if(!LoadPemCertAndKeyByMemory(sslCtx, lpszPemCert, lpszPemKey, lpszKeyPassword))
  313. return FALSE;
  314. return TRUE;
  315. }
  316. BOOL CSSLContext::LoadCAPemCertByMemory(SSL_CTX* sslCtx, int iVerifyMode, LPCSTR lpszCAPemCert)
  317. {
  318. if(::IsStrEmptyA(lpszCAPemCert))
  319. return TRUE;
  320. if(!AddCAPemCertToStoreByMemory(sslCtx, lpszCAPemCert))
  321. return FALSE;
  322. if(!SSL_CTX_set_default_verify_paths(sslCtx))
  323. {
  324. ::SetLastError(ERROR_FUNCTION_FAILED);
  325. return FALSE;
  326. }
  327. if(m_enSessionMode == SSL_SM_SERVER && (iVerifyMode & SSL_VM_PEER))
  328. {
  329. if(!SetClientCAListByMemory(sslCtx, lpszCAPemCert))
  330. return FALSE;
  331. }
  332. return TRUE;
  333. }
  334. BOOL CSSLContext::LoadPemCertAndKeyByMemory(SSL_CTX* sslCtx, LPCSTR lpszPemCert, LPCSTR lpszPemKey, LPCSTR lpszKeyPassword)
  335. {
  336. if(::IsStrEmptyA(lpszPemCert))
  337. return TRUE;
  338. if(::IsStrEmptyA(lpszPemKey))
  339. {
  340. ::SetLastError(ERROR_INVALID_PARAMETER);
  341. return FALSE;
  342. }
  343. if(::IsStrNotEmptyA(lpszKeyPassword))
  344. SSL_CTX_set_default_passwd_cb_userdata(sslCtx, (void*)(lpszKeyPassword));
  345. if(!SetPrivateKeyByMemory(sslCtx, lpszPemKey))
  346. return FALSE;
  347. if(!SetCertChainByMemory(sslCtx, lpszPemCert))
  348. return FALSE;
  349. if(!SSL_CTX_check_private_key(sslCtx))
  350. {
  351. ::SetLastError(ERROR_INVALID_ACCESS);
  352. return FALSE;
  353. }
  354. return TRUE;
  355. }
  356. BOOL CSSLContext::AddCAPemCertToStoreByMemory(SSL_CTX* sslCtx, LPCSTR lpszPemCert)
  357. {
  358. BOOL isOK = FALSE;
  359. int iCount = 0;
  360. BIO* pBIO = BIO_new_mem_buf(lpszPemCert, -1);
  361. X509_STORE* pStore = SSL_CTX_get_cert_store(sslCtx);
  362. STACK_OF(X509_INFO) * pStack = nullptr;
  363. if(pBIO == nullptr)
  364. {
  365. ::SetLastError(ERROR_CREATE_FAILED);
  366. goto _END;
  367. }
  368. if(pStore == nullptr)
  369. {
  370. ::SetLastError(ERROR_NOT_FOUND);
  371. goto _END;
  372. }
  373. pStack = PEM_X509_INFO_read_bio(pBIO, nullptr, nullptr, nullptr);
  374. if(pStack == nullptr)
  375. {
  376. ::SetLastError(ERROR_NO_DATA);
  377. goto _END;
  378. }
  379. for(int i = 0; i < sk_X509_INFO_num(pStack); i++)
  380. {
  381. X509_INFO* pInfo = sk_X509_INFO_value(pStack, i);
  382. if(pInfo->x509)
  383. {
  384. if(!X509_STORE_add_cert(pStore, pInfo->x509))
  385. {
  386. ::SetLastError(ERROR_INVALID_DATA);
  387. goto _END;
  388. }
  389. ++iCount;
  390. }
  391. if(pInfo->crl)
  392. {
  393. if(!X509_STORE_add_crl(pStore, pInfo->crl))
  394. {
  395. ::SetLastError(ERROR_INVALID_DATA);
  396. goto _END;
  397. }
  398. ++iCount;
  399. }
  400. }
  401. if(iCount > 0)
  402. isOK = TRUE;
  403. else
  404. ::SetLastError(ERROR_EMPTY);
  405. _END:
  406. if(pStack != nullptr)
  407. sk_X509_INFO_pop_free(pStack, X509_INFO_free);
  408. if(pBIO != nullptr)
  409. BIO_free(pBIO);
  410. return isOK;
  411. }
  412. BOOL CSSLContext::SetClientCAListByMemory(SSL_CTX* sslCtx, LPCSTR lpszPemCert)
  413. {
  414. BOOL isOK = FALSE;
  415. X509* pX509 = nullptr;
  416. X509_NAME* pName = nullptr;
  417. STACK_OF(X509_NAME)* pStack = nullptr;
  418. BIO* pBIO = BIO_new_mem_buf(lpszPemCert, -1);
  419. OPENSSL_LHASH* pNameHash = (OPENSSL_LHASH*)OPENSSL_LH_new((OPENSSL_LH_HASHFUNC)FN_X509_NAME_HASH, (OPENSSL_LH_COMPFUNC)X509_NAME_cmp);
  420. if(pBIO == nullptr || pNameHash == nullptr)
  421. {
  422. ::SetLastError(ERROR_CREATE_FAILED);
  423. goto _ERR;
  424. }
  425. while(TRUE)
  426. {
  427. if(PEM_read_bio_X509(pBIO, &pX509, nullptr, nullptr) == nullptr)
  428. break;
  429. if(pStack == nullptr)
  430. {
  431. pStack = sk_X509_NAME_new_null();
  432. if(pStack == nullptr)
  433. {
  434. ::SetLastError(ERROR_CREATE_FAILED);
  435. goto _ERR;
  436. }
  437. }
  438. if((pName = X509_get_subject_name(pX509)) == nullptr)
  439. {
  440. ::SetLastError(ERROR_NO_DATA);
  441. goto _ERR;
  442. }
  443. if((pName = X509_NAME_dup(pName)) == nullptr)
  444. {
  445. ::SetLastError(ERROR_CREATE_FAILED);
  446. goto _ERR;
  447. }
  448. if(OPENSSL_LH_retrieve(pNameHash, pName) != nullptr)
  449. {
  450. X509_NAME_free(pName);
  451. pName = nullptr;
  452. }
  453. else
  454. {
  455. OPENSSL_LH_insert(pNameHash, pName);
  456. if(!sk_X509_NAME_push(pStack, pName))
  457. {
  458. ::SetLastError(ERROR_WRITE_FAULT);
  459. goto _ERR;
  460. }
  461. }
  462. }
  463. if(pStack == nullptr)
  464. {
  465. ::SetLastError(ERROR_EMPTY);
  466. goto _ERR;
  467. }
  468. SSL_CTX_set_client_CA_list(sslCtx, pStack);
  469. isOK = TRUE;
  470. goto _END;
  471. _ERR:
  472. if(pName != nullptr)
  473. X509_NAME_free(pName);
  474. if(pStack != nullptr)
  475. {
  476. sk_X509_NAME_pop_free(pStack, X509_NAME_free);
  477. pStack = nullptr;
  478. }
  479. _END:
  480. if(pX509 != nullptr)
  481. X509_free(pX509);
  482. if(pNameHash != nullptr)
  483. OPENSSL_LH_free(pNameHash);
  484. if(pBIO != nullptr)
  485. BIO_free(pBIO);
  486. if(pStack != nullptr)
  487. ERR_clear_error();
  488. return isOK;
  489. }
  490. BOOL CSSLContext::SetPrivateKeyByMemory(SSL_CTX* sslCtx, LPCSTR lpszPemKey)
  491. {
  492. BOOL isOK = FALSE;
  493. BIO* pBIO = BIO_new_mem_buf(lpszPemKey, -1);
  494. EVP_PKEY* pKey = nullptr;
  495. if(pBIO == nullptr)
  496. {
  497. ::SetLastError(ERROR_CREATE_FAILED);
  498. goto _END;
  499. }
  500. pKey = PEM_read_bio_PrivateKey(pBIO, nullptr, SSL_CTX_get_default_passwd_cb(sslCtx), SSL_CTX_get_default_passwd_cb_userdata(sslCtx));
  501. if(pKey == nullptr)
  502. {
  503. ::SetLastError(ERROR_INVALID_PASSWORD);
  504. goto _END;
  505. }
  506. if(!SSL_CTX_use_PrivateKey(sslCtx, pKey))
  507. {
  508. ::SetLastError(ERROR_INVALID_DATA);
  509. goto _END;
  510. }
  511. isOK = TRUE;
  512. _END:
  513. if(pKey != nullptr)
  514. EVP_PKEY_free(pKey);
  515. if(pBIO != nullptr)
  516. BIO_free(pBIO);
  517. return isOK;
  518. }
  519. BOOL CSSLContext::SetCertChainByMemory(SSL_CTX* sslCtx, LPCSTR lpszPemCert)
  520. {
  521. BOOL isOK = FALSE;
  522. ULONG err = 0;
  523. BIO* pBIO = BIO_new_mem_buf(lpszPemCert, -1);
  524. X509* pX509 = nullptr;
  525. pem_password_cb* cb = SSL_CTX_get_default_passwd_cb(sslCtx);
  526. LPVOID userdata = SSL_CTX_get_default_passwd_cb_userdata(sslCtx);
  527. if(pBIO == nullptr)
  528. {
  529. ::SetLastError(ERROR_CREATE_FAILED);
  530. goto _END;
  531. }
  532. pX509 = PEM_read_bio_X509_AUX(pBIO, nullptr, cb, userdata);
  533. if(pX509 == nullptr)
  534. {
  535. ::SetLastError(ERROR_NO_DATA);
  536. goto _END;
  537. }
  538. if(!SSL_CTX_use_certificate(sslCtx, pX509) || (ERR_peek_error() != 0))
  539. {
  540. ::SetLastError(ERROR_INVALID_DATA);
  541. goto _END;
  542. }
  543. if(!SSL_CTX_clear_chain_certs(sslCtx))
  544. {
  545. ::SetLastError(ERROR_FUNCTION_FAILED);
  546. goto _END;
  547. }
  548. X509* pCA;
  549. while((pCA = PEM_read_bio_X509(pBIO, nullptr, cb, userdata)) != nullptr)
  550. {
  551. if(!SSL_CTX_add0_chain_cert(sslCtx, pCA))
  552. {
  553. X509_free(pCA);
  554. ::SetLastError(ERROR_FUNCTION_FAILED);
  555. goto _END;
  556. }
  557. }
  558. err = ERR_peek_last_error();
  559. if(ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)
  560. ERR_clear_error();
  561. else
  562. {
  563. ::SetLastError(ERROR_FUNCTION_FAILED);
  564. goto _END;
  565. }
  566. isOK = TRUE;
  567. _END:
  568. if(pX509 != nullptr)
  569. X509_free(pX509);
  570. if(pBIO != nullptr)
  571. BIO_free(pBIO);
  572. return isOK;
  573. }
  574. void CSSLContext::Cleanup()
  575. {
  576. if(IsValid())
  577. {
  578. int iCount = (int)m_lsSslCtxs.size();
  579. for(int i = 0; i < iCount; i++)
  580. SSL_CTX_free(m_lsSslCtxs[i]);
  581. m_lsSslCtxs.clear();
  582. m_sslServerNames.clear();
  583. m_sslCtx = nullptr;
  584. }
  585. m_fnServerNameCallback = nullptr;
  586. RemoveThreadLocalState();
  587. }
  588. void CSSLContext::SetServerNameCallback(Fn_SNI_ServerNameCallback fn)
  589. {
  590. if(m_enSessionMode != SSL_SM_SERVER)
  591. return;
  592. if(fn == nullptr)
  593. m_fnServerNameCallback = DefaultServerNameCallback;
  594. else
  595. m_fnServerNameCallback = fn;
  596. VERIFY(SSL_CTX_set_tlsext_servername_callback(m_sslCtx, InternalServerNameCallback));
  597. VERIFY(SSL_CTX_set_tlsext_servername_arg(m_sslCtx, this));
  598. }
  599. int CSSLContext::InternalServerNameCallback(SSL* ssl, int* ad, void* arg)
  600. {
  601. USES_CONVERSION;
  602. CSSLContext* pThis = (CSSLContext*)arg;
  603. ASSERT(pThis->m_fnServerNameCallback != nullptr);
  604. const char* lpszServerName = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  605. if(lpszServerName == nullptr)
  606. return SSL_TLSEXT_ERR_NOACK;
  607. int iIndex = pThis->m_fnServerNameCallback(A2CT(lpszServerName), pThis);
  608. if(iIndex == 0)
  609. return SSL_TLSEXT_ERR_OK;
  610. if(iIndex < 0)
  611. {
  612. ::SetLastError(ERROR_INVALID_NAME);
  613. return SSL_TLSEXT_ERR_ALERT_FATAL;
  614. }
  615. SSL_CTX* sslCtx = pThis->GetContext(iIndex);
  616. if(sslCtx == nullptr)
  617. {
  618. ::SetLastError(ERROR_INVALID_INDEX);
  619. return SSL_TLSEXT_ERR_ALERT_FATAL;
  620. }
  621. SSL_set_SSL_CTX(ssl, sslCtx);
  622. return SSL_TLSEXT_ERR_OK;
  623. }
  624. int __HP_CALL CSSLContext::DefaultServerNameCallback(LPCTSTR lpszServerName, PVOID pContext)
  625. {
  626. CSSLContext* pThis = (CSSLContext*)pContext;
  627. if(pThis->m_sslServerNames.empty())
  628. return 0;
  629. LPCTSTR lpszTmp = lpszServerName;
  630. LPCTSTR lpszSep = ::StrChr(lpszTmp, SSL_DOMAIN_SEP_CHAR);
  631. while(lpszSep != nullptr)
  632. {
  633. CServerNameMap::const_iterator it = pThis->m_sslServerNames.find(lpszTmp);
  634. if(it != pThis->m_sslServerNames.end())
  635. return it->second;
  636. lpszTmp = (lpszSep + 1);
  637. lpszSep = ::StrChr(lpszTmp, SSL_DOMAIN_SEP_CHAR);
  638. }
  639. return 0;
  640. }
  641. SSL_CTX* CSSLContext::GetContext(int i) const
  642. {
  643. SSL_CTX* sslCtx = nullptr;
  644. if(i >= 0 && i < (int)m_lsSslCtxs.size())
  645. sslCtx = m_lsSslCtxs[i];
  646. return sslCtx;
  647. }
  648. BOOL CSSLSession::WriteRecvChannel(const BYTE* pData, int iLength)
  649. {
  650. ASSERT(pData && iLength > 0);
  651. BOOL isOK = TRUE;
  652. int bytes = BIO_write(m_bioRecv, pData, iLength);
  653. if(bytes > 0)
  654. ASSERT(bytes == iLength);
  655. else if(!BIO_should_retry(m_bioRecv))
  656. {
  657. ::SetLastError(ERROR_INVALID_DATA);
  658. isOK = FALSE;
  659. }
  660. return isOK;
  661. }
  662. BOOL CSSLSession::ReadRecvChannel()
  663. {
  664. BOOL isOK = TRUE;
  665. int bytes = SSL_read(m_ssl, m_bufRecv.buf, m_pitRecv->Capacity());
  666. if(bytes > 0)
  667. m_bufRecv.len = bytes;
  668. else if(!IsFatalError(bytes))
  669. m_bufRecv.len = 0;
  670. else
  671. isOK = FALSE;
  672. if(isOK && m_enStatus == SSL_HSS_PROC && SSL_is_init_finished(m_ssl))
  673. m_enStatus = SSL_HSS_SUCC;
  674. return isOK;
  675. }
  676. BOOL CSSLSession::WriteSendChannel(const BYTE* pData, int iLength)
  677. {
  678. ASSERT(IsReady());
  679. ASSERT(pData && iLength > 0);
  680. BOOL isOK = TRUE;
  681. int bytes = SSL_write(m_ssl, pData, iLength);
  682. if(bytes > 0)
  683. ASSERT(bytes == iLength);
  684. else if(IsFatalError(bytes))
  685. isOK = FALSE;
  686. return isOK;
  687. }
  688. BOOL CSSLSession::WriteSendChannel(const WSABUF pBuffers[], int iCount)
  689. {
  690. ASSERT(pBuffers && iCount > 0);
  691. BOOL isOK = TRUE;
  692. for(int i = 0; i < iCount; i++)
  693. {
  694. const WSABUF& buffer = pBuffers[i];
  695. if(buffer.len > 0)
  696. {
  697. if(!WriteSendChannel((const BYTE*)buffer.buf, buffer.len))
  698. {
  699. isOK = FALSE;
  700. break;
  701. }
  702. }
  703. }
  704. return isOK;
  705. }
  706. BOOL CSSLSession::ReadSendChannel()
  707. {
  708. if(BIO_pending(m_bioSend) == 0)
  709. {
  710. m_bufSend.len = 0;
  711. return TRUE;
  712. }
  713. BOOL isOK = TRUE;
  714. int bytes = BIO_read(m_bioSend, m_bufSend.buf, m_pitSend->Capacity());
  715. if(bytes > 0)
  716. m_bufSend.len = bytes;
  717. else if(BIO_should_retry(m_bioSend))
  718. m_bufSend.len = 0;
  719. else
  720. {
  721. ::SetLastError(ERROR_INVALID_DATA);
  722. isOK = FALSE;
  723. }
  724. return isOK;
  725. }
  726. CSSLSession* CSSLSession::Renew(const CSSLContext& sslCtx, LPCSTR lpszHostName)
  727. {
  728. ASSERT(!IsValid());
  729. ResetCount();
  730. m_ssl = SSL_new(sslCtx.GetDefaultContext());
  731. m_bioSend = BIO_new(BIO_s_mem());
  732. m_bioRecv = BIO_new(BIO_s_mem());
  733. SSL_set_bio(m_ssl, m_bioRecv, m_bioSend);
  734. if(sslCtx.GetSessionMode() == SSL_SM_SERVER)
  735. SSL_accept(m_ssl);
  736. else
  737. {
  738. USES_CONVERSION;
  739. if(lpszHostName && lpszHostName[0] != 0 && !::IsIPAddress(A2CT(lpszHostName)))
  740. SSL_set_tlsext_host_name(m_ssl, lpszHostName);
  741. SSL_connect(m_ssl);
  742. }
  743. m_pitSend = m_itPool.PickFreeItem();
  744. m_pitRecv = m_itPool.PickFreeItem();
  745. m_bufSend.buf = m_pitSend->Ptr();
  746. m_bufRecv.buf = m_pitRecv->Ptr();
  747. m_enStatus = SSL_HSS_PROC;
  748. return this;
  749. }
  750. BOOL CSSLSession::Reset()
  751. {
  752. BOOL isOK = FALSE;
  753. if(IsValid())
  754. {
  755. CCriSecLock locallock(m_csSend);
  756. if(IsValid())
  757. {
  758. m_enStatus = SSL_HSS_INIT;
  759. SSL_shutdown(m_ssl);
  760. SSL_free(m_ssl);
  761. m_itPool.PutFreeItem(m_pitSend);
  762. m_itPool.PutFreeItem(m_pitRecv);
  763. m_pitSend = nullptr;
  764. m_pitRecv = nullptr;
  765. m_ssl = nullptr;
  766. m_bioSend = nullptr;
  767. m_bioRecv = nullptr;
  768. m_dwFreeTime= ::TimeGetTime();
  769. isOK = TRUE;
  770. }
  771. }
  772. ERR_clear_error();
  773. return isOK;
  774. }
  775. inline BOOL CSSLSession::IsFatalError(int iBytes)
  776. {
  777. int iErrorCode = SSL_get_error(m_ssl, iBytes);
  778. if( iErrorCode == SSL_ERROR_NONE ||
  779. iErrorCode == SSL_ERROR_WANT_READ ||
  780. iErrorCode == SSL_ERROR_WANT_WRITE ||
  781. iErrorCode == SSL_ERROR_WANT_CONNECT ||
  782. iErrorCode == SSL_ERROR_WANT_ACCEPT )
  783. return FALSE;
  784. #ifdef _DEBUG
  785. char szBuffer[512];
  786. #endif
  787. int i = 0;
  788. ULONG iCode = iErrorCode;
  789. for(; iCode != SSL_ERROR_NONE; i++)
  790. {
  791. #ifdef _DEBUG
  792. ERR_error_string_n(iCode, szBuffer, sizeof(szBuffer));
  793. TRACE(" > SSL Error: %ld - %s\n", iCode, szBuffer);
  794. #endif
  795. iCode = ERR_get_error();
  796. }
  797. if(iErrorCode == SSL_ERROR_SYSCALL && i == 1)
  798. return FALSE;
  799. ::SetLastError(ERROR_INVALID_DATA);
  800. return TRUE;
  801. }
  802. BOOL CSSLSession::GetSessionInfo(EnSSLSessionInfo enInfo, LPVOID* lppInfo)
  803. {
  804. ASSERT(lppInfo != nullptr);
  805. *lppInfo = nullptr;
  806. if(enInfo < SSL_SSI_MIN || enInfo > SSL_SSI_MAX)
  807. {
  808. ::SetLastError(ERROR_INVALID_PARAMETER);
  809. return FALSE;
  810. }
  811. if(!IsValid())
  812. {
  813. ::SetLastError(ERROR_INVALID_STATE);
  814. return FALSE;
  815. }
  816. SSL_CTX* pContext = SSL_get_SSL_CTX(m_ssl);
  817. switch(enInfo)
  818. {
  819. case SSL_SSI_CTX:
  820. {
  821. *lppInfo = (LPVOID)(pContext);
  822. }
  823. break;
  824. case SSL_SSI_CTX_METHOD:
  825. {
  826. if(pContext != nullptr)
  827. *lppInfo = (LPVOID)(SSL_CTX_get_ssl_method(pContext));
  828. }
  829. break;
  830. case SSL_SSI_CTX_CIPHERS:
  831. {
  832. if(pContext != nullptr)
  833. *lppInfo = (LPVOID)(SSL_CTX_get_ciphers(pContext));
  834. }
  835. break;
  836. case SSL_SSI_CTX_CERT_STORE:
  837. {
  838. if(pContext != nullptr)
  839. *lppInfo = (LPVOID)(SSL_CTX_get_cert_store(pContext));
  840. }
  841. break;
  842. case SSL_SSI_SERVER_NAME_TYPE:
  843. {
  844. *lppInfo = (LPVOID)(UINT_PTR)(SSL_get_servername_type(m_ssl));
  845. }
  846. break;
  847. case SSL_SSI_SERVER_NAME:
  848. {
  849. int type = SSL_get_servername_type(m_ssl);
  850. if(type != -1)
  851. *lppInfo = (LPVOID)(SSL_get_servername(m_ssl, type));
  852. }
  853. break;
  854. case SSL_SSI_VERSION:
  855. {
  856. *lppInfo = (LPVOID)(SSL_get_version(m_ssl));
  857. }
  858. break;
  859. case SSL_SSI_METHOD:
  860. {
  861. *lppInfo = (LPVOID)(SSL_get_ssl_method(m_ssl));
  862. }
  863. break;
  864. case SSL_SSI_CERT:
  865. {
  866. *lppInfo = (LPVOID)(SSL_get_certificate(m_ssl));
  867. }
  868. break;
  869. case SSL_SSI_PKEY:
  870. {
  871. *lppInfo = (LPVOID)(SSL_get_privatekey(m_ssl));
  872. }
  873. break;
  874. case SSL_SSI_CURRENT_CIPHER:
  875. {
  876. *lppInfo = (LPVOID)(SSL_get_current_cipher(m_ssl));
  877. }
  878. break;
  879. case SSL_SSI_CIPHERS:
  880. {
  881. *lppInfo = (LPVOID)(SSL_get_ciphers(m_ssl));
  882. }
  883. break;
  884. case SSL_SSI_CLIENT_CIPHERS:
  885. {
  886. *lppInfo = (LPVOID)(SSL_get_client_ciphers(m_ssl));
  887. }
  888. break;
  889. case SSL_SSI_PEER_CERT:
  890. {
  891. X509* pCert = SSL_get_peer_certificate(m_ssl);
  892. if(pCert != nullptr)
  893. {
  894. *lppInfo = (LPVOID*)pCert;
  895. X509_free(pCert);
  896. }
  897. }
  898. break;
  899. case SSL_SSI_PEER_CERT_CHAIN:
  900. {
  901. *lppInfo = (LPVOID)(SSL_get_peer_cert_chain(m_ssl));
  902. }
  903. break;
  904. case SSL_SSI_VERIFIED_CHAIN:
  905. {
  906. *lppInfo = (LPVOID)(SSL_get0_verified_chain(m_ssl));
  907. }
  908. break;
  909. }
  910. return TRUE;
  911. }
  912. CSSLSession* CSSLSessionPool::PickFreeSession(LPCSTR lpszHostName)
  913. {
  914. DWORD dwIndex;
  915. CSSLSession* pSession = nullptr;
  916. if(m_lsFreeSession.TryLock(&pSession, dwIndex))
  917. {
  918. if(::GetTimeGap32(pSession->GetFreeTime()) >= m_dwSessionLockTime)
  919. VERIFY(m_lsFreeSession.ReleaseLock(nullptr, dwIndex));
  920. else
  921. {
  922. VERIFY(m_lsFreeSession.ReleaseLock(pSession, dwIndex));
  923. pSession = nullptr;
  924. }
  925. }
  926. if(!pSession) pSession = CSSLSession::Construct(m_itPool);
  927. ASSERT(pSession);
  928. return pSession->Renew(m_sslCtx, lpszHostName);
  929. }
  930. void CSSLSessionPool::PutFreeSession(CSSLSession* pSession)
  931. {
  932. if(pSession->Reset())
  933. {
  934. #ifndef USE_EXTERNAL_GC
  935. ReleaseGCSession();
  936. #endif
  937. if(!m_lsFreeSession.TryPut(pSession))
  938. m_lsGCSession.PushBack(pSession);
  939. }
  940. }
  941. void CSSLSessionPool::Prepare()
  942. {
  943. m_itPool.Prepare();
  944. m_lsFreeSession.Reset(m_dwSessionPoolSize);
  945. }
  946. void CSSLSessionPool::Clear()
  947. {
  948. m_lsFreeSession.Clear();
  949. ReleaseGCSession(TRUE);
  950. VERIFY(m_lsGCSession.IsEmpty());
  951. m_itPool.Clear();
  952. }
  953. void CSSLSessionPool::ReleaseGCSession(BOOL bForce)
  954. {
  955. ::ReleaseGCObj(m_lsGCSession, m_dwSessionLockTime, bForce);
  956. }
  957. #endif