securesocket.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. // Some ssl prototypes use char* where they should be using const char *, resulting in lots of spurious warnings
  14. #ifndef _MSC_VER
  15. #pragma GCC diagnostic ignored "-Wwrite-strings"
  16. #endif
  17. //jlib
  18. #include "jliball.hpp"
  19. #include "string.h"
  20. #ifdef _WIN32
  21. #include <windows.h>
  22. #include <winsock2.h>
  23. #include <ws2tcpip.h>
  24. #else
  25. #include <sys/types.h>
  26. #include <sys/socket.h>
  27. #include <netinet/tcp.h>
  28. #include <netinet/in.h>
  29. #include <arpa/inet.h>
  30. #include <stddef.h>
  31. #include <errno.h>
  32. #endif
  33. #include <signal.h>
  34. //openssl
  35. #include <openssl/rsa.h>
  36. #include <openssl/crypto.h>
  37. #ifndef _WIN32
  38. //x509.h includes evp.h, which in turn includes des.h which defines
  39. //crypt() that throws different exception than in unistd.h
  40. //(this causes build break on linux) so exclude it
  41. #define crypt DONT_DEFINE_CRYPT
  42. #include <openssl/x509.h>
  43. #undef crypt
  44. #else
  45. #include <openssl/x509.h>
  46. #endif
  47. #include <openssl/ssl.h>
  48. #include <openssl/pem.h>
  49. #include <openssl/err.h>
  50. #include <openssl/conf.h>
  51. #include <openssl/x509v3.h>
  52. #include "jsmartsock.ipp"
  53. #include "securesocket.hpp"
  54. static JSocketStatistics *SSTATS;
  55. #define CHK_NULL(x) if((x)==NULL) exit(1)
  56. #define CHK_ERR(err, s) if((err)==-1){perror(s);exit(1);}
  57. #define CHK_SSL(err) if((err) ==-1){ERR_print_errors_fp(stderr); exit(2);}
  58. #define THROWSECURESOCKETEXCEPTION(err) \
  59. throw MakeStringException(-1, "SecureSocket Exception Raised in: %s, line %d - %s", sanitizeSourceFile(__FILE__), __LINE__, err);
  60. static int pem_passwd_cb(char* buf, int size, int rwflag, void* password)
  61. {
  62. strncpy(buf, (char*)password, size);
  63. buf[size - 1] = '\0';
  64. return(strlen(buf));
  65. }
  66. static void readBio(BIO* bio, StringBuffer& buf)
  67. {
  68. char readbuf[1024];
  69. int len = 0;
  70. while((len = BIO_read(bio, readbuf, 1024)) > 0)
  71. {
  72. buf.append(len, readbuf);
  73. }
  74. }
  75. //Use a namespace to prevent clashes with a class of the same name in jhtree
  76. namespace securesocket
  77. {
  78. class CStringSet : public CInterface
  79. {
  80. class StringHolder : public CInterface
  81. {
  82. public:
  83. StringBuffer m_str;
  84. StringHolder(const char* str)
  85. {
  86. m_str.clear().append(str);
  87. }
  88. const char *queryFindString() const { return m_str.str(); }
  89. };
  90. private:
  91. OwningStringSuperHashTableOf<StringHolder> strhash;
  92. public:
  93. void add(const char* val)
  94. {
  95. StringHolder* h1 = strhash.find(val);
  96. if(h1 == NULL)
  97. strhash.add(*(new StringHolder(val)));
  98. }
  99. bool contains(const char* val)
  100. {
  101. StringHolder* h1 = strhash.find(val);
  102. return (h1 != NULL);
  103. }
  104. };
  105. class CSecureSocket : implements ISecureSocket, public CInterface
  106. {
  107. private:
  108. SSL* m_ssl;
  109. Owned<ISocket> m_socket;
  110. bool m_verify;
  111. bool m_address_match;
  112. CStringSet* m_peers;
  113. int m_loglevel;
  114. bool m_isSecure;
  115. StringBuffer m_fqdn;
  116. size32_t nextblocksize = 0;
  117. unsigned blockflags = BF_ASYNC_TRANSFER;
  118. unsigned blocktimeoutms = WAIT_FOREVER;
  119. #ifdef USERECVSEM
  120. static Semaphore receiveblocksem;
  121. bool receiveblocksemowned; // owned by this socket
  122. #endif
  123. private:
  124. StringBuffer& get_cn(X509* cert, StringBuffer& cn);
  125. bool verify_cert(X509* cert);
  126. public:
  127. IMPLEMENT_IINTERFACE;
  128. CSecureSocket(ISocket* sock, SSL_CTX* ctx, bool verify = false, bool addres_match = false, CStringSet* m_peers = NULL, int loglevel=SSLogNormal, const char *fqdn = nullptr);
  129. CSecureSocket(int sockfd, SSL_CTX* ctx, bool verify = false, bool addres_match = false, CStringSet* m_peers = NULL, int loglevel=SSLogNormal, const char *fqdn = nullptr);
  130. ~CSecureSocket();
  131. virtual int secure_accept(int logLevel);
  132. virtual int secure_connect(int logLevel);
  133. virtual int logPollError(unsigned revents, const char *rwstr);
  134. virtual int wait_read(unsigned timeoutms);
  135. virtual void read(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read,unsigned timeoutsecs);
  136. virtual void readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, unsigned timeoutms);
  137. virtual size32_t write(void const* buf, size32_t size);
  138. virtual size32_t writetms(void const* buf, size32_t size, unsigned timeoutms=WAIT_FOREVER);
  139. void readTimeout(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, unsigned timeout, bool useSeconds);
  140. virtual StringBuffer& get_ssl_version(StringBuffer& ver)
  141. {
  142. ver.set(SSL_get_version(m_ssl));
  143. return ver;
  144. }
  145. //The following are the functions from ISocket that haven't been implemented.
  146. virtual void read(void* buf, size32_t size)
  147. {
  148. size32_t size_read;
  149. // MCK - this was:
  150. // readTimeout(buf, size, size, size_read, 0, false);
  151. // but that is essentially a non-blocking read() and we want a blocking read() ...
  152. // read() is always expecting size bytes so min_size should be size
  153. readTimeout(buf, size, size, size_read, WAIT_FOREVER, false);
  154. }
  155. virtual size32_t get_max_send_size()
  156. {
  157. throw MakeStringException(-1, "CSecureSocket::get_max_send_size: not implemented");
  158. }
  159. //
  160. // This method is called by server to accept client connection
  161. //
  162. virtual ISocket* accept(bool allowcancel=false, SocketEndpoint *peerEp=nullptr) // not needed for UDP
  163. {
  164. throw MakeStringException(-1, "CSecureSocket::accept: not implemented");
  165. }
  166. //
  167. // This method is called to check whether a socket is ready to write (i.e. some free buffer space)
  168. //
  169. virtual int wait_write(unsigned timeout)
  170. {
  171. return m_socket->wait_write(timeout);
  172. }
  173. //
  174. // can be used with write to allow it to return if it would block
  175. // be sure and restore to old state before calling other functions on this socket
  176. //
  177. virtual bool set_nonblock(bool on) // returns old state
  178. {
  179. throw MakeStringException(-1, "CSecureSocket::set_nonblock: not implemented");
  180. }
  181. // enable 'nagling' - small packet coalescing (implies delayed transmission)
  182. //
  183. virtual bool set_nagle(bool on) // returns old state
  184. {
  185. throw MakeStringException(-1, "CSecureSocket::set_nagle: not implemented");
  186. }
  187. // set 'linger' time - time close will linger so that outstanding unsent data will be transmited
  188. //
  189. virtual void set_linger(int lingersecs)
  190. {
  191. m_socket->set_linger(lingersecs);
  192. }
  193. //
  194. // Cancel accept operation and close socket
  195. //
  196. virtual void cancel_accept() // not needed for UDP
  197. {
  198. m_socket->cancel_accept();
  199. }
  200. //
  201. // Shutdown socket: prohibit write and read operations on socket
  202. //
  203. virtual void shutdown(unsigned mode) // not needed for UDP
  204. {
  205. m_socket->shutdown(mode);
  206. }
  207. // Get local name of accepted (or connected) socket and returns port
  208. virtual int name(char *name,size32_t namemax)
  209. {
  210. return m_socket->name(name, namemax);
  211. }
  212. // Get peer name of socket and returns port - in UDP returns return addr
  213. virtual int peer_name(char *name,size32_t namemax)
  214. {
  215. return m_socket->peer_name(name, namemax);
  216. }
  217. // Get peer endpoint of socket - in UDP returns return addr
  218. virtual SocketEndpoint &getPeerEndpoint(SocketEndpoint &ep)
  219. {
  220. return m_socket->getPeerEndpoint(ep);
  221. }
  222. // Get peer ip of socket - in UDP returns return addr
  223. virtual IpAddress &getPeerAddress(IpAddress &addr)
  224. {
  225. return m_socket->getPeerAddress(addr);
  226. }
  227. // Get local endpoint of socket
  228. virtual SocketEndpoint &getEndpoint(SocketEndpoint &ep) const override
  229. {
  230. return m_socket->getEndpoint(ep);
  231. }
  232. //
  233. // Close socket
  234. //
  235. virtual bool connectionless() // true if accept need not be called (i.e. UDP)
  236. {
  237. throw MakeStringException(-1, "CSecureSocket::connectionless: not implemented");
  238. }
  239. virtual void set_return_addr(int port,const char *name) // used for UDP servers only
  240. {
  241. throw MakeStringException(-1, "CSecureSocket::set_return_addr: not implemented");
  242. }
  243. // Block functions
  244. // TLS TODO: can we move these block* into a base class for both CSocket and CSecureSocket ?
  245. virtual void set_block_mode( // must be called before block operations
  246. unsigned flags, // BF_* flags (must match receive_block)
  247. size32_t recsize=0, // record size (required for rec compression)
  248. unsigned timeout=0 // timeout in msecs (0 for no timeout)
  249. );
  250. virtual bool send_block(
  251. const void *blk, // data to send
  252. size32_t sz // size to send (0 for eof)
  253. );
  254. virtual size32_t receive_block_size(); // get size of next block (always must call receive_block after)
  255. virtual size32_t receive_block(
  256. void *blk, // receive pointer
  257. size32_t sz // max size to read (0 for sync eof)
  258. ); // if less than block size truncates block
  259. virtual void close()
  260. {
  261. m_socket->close();
  262. }
  263. virtual unsigned OShandle() const // for internal use
  264. {
  265. return m_socket->OShandle();
  266. }
  267. virtual bool isValid() const
  268. {
  269. return m_socket->isValid();
  270. }
  271. virtual size32_t avail_read() // called after wait_read to see how much data available
  272. {
  273. int pending = SSL_pending(m_ssl);
  274. if(pending > 0)
  275. return pending;
  276. // pending == 0 : check if there still might be data to read
  277. // (often used as a check for if socket was closed by peer)
  278. size32_t avr = m_socket->avail_read();
  279. if (avr > 0)
  280. {
  281. // TLS TODO: MCK - needs to be thought out and refactored
  282. // Bytes here may be part of encrypted SSL record.
  283. // If SSL_MODE_AUTO_RETRY set (and it is) then bytes
  284. // here may also be from auto-renegotiation.
  285. // If return 0 here, caller may think socket was closed
  286. // If return >0 here, caller may block on next SSL_read()
  287. // Only two locations where this value other than !=0 is used:
  288. // CRemoteFileServer->notifySelected() (dafsserver)
  289. // CMPPacketReader->notifySelected() (mpcomm)
  290. return 1;
  291. /* --------------------------------
  292. // bytes may be SSL/TLS protocol and not part of msg
  293. byte c[2];
  294. // TODO this may block ...
  295. pending = SSL_peek(m_ssl, c, 1);
  296. // 0 almost always means socket was closed
  297. if (pending == 0)
  298. return 0;
  299. if (pending > 0)
  300. return SSL_pending(m_ssl);
  301. // pending < 0 : TODO should handle SSL_ERROR_WANT_READ/WRITE error
  302. if (m_loglevel >= SSLogNormal)
  303. {
  304. int ret = SSL_get_error(m_ssl, pending);
  305. char errbuf[512];
  306. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  307. errbuf[511] = '\0';
  308. DBGLOG("SSL_peek (avail_read) returns error %d - %s", ret, errbuf);
  309. }
  310. -------------------------------- */
  311. }
  312. return 0;
  313. }
  314. virtual size32_t write_multiple(unsigned num, const void **buf, size32_t *size)
  315. {
  316. size32_t res = 0;
  317. for (int i=0; i<num; i++)
  318. {
  319. if (size[i] > 0)
  320. {
  321. // non-tls version tries to write equal 64k chunks, but unless we set
  322. // SSL_MODE_ENABLE_PARTIAL_WRITE, we should write each buf[i] entirely ...
  323. res += write(buf[i], size[i]);
  324. }
  325. }
  326. return res;
  327. }
  328. virtual size32_t get_send_buffer_size() // get OS send buffer
  329. {
  330. throw MakeStringException(-1, "CSecureSocket::get_send_buffer_size: not implemented");
  331. }
  332. void set_send_buffer_size(size32_t sz) // set OS send buffer size
  333. {
  334. throw MakeStringException(-1, "CSecureSocket::set_send_buffer_size: not implemented");
  335. }
  336. bool join_multicast_group(SocketEndpoint &ep) // for udp multicast
  337. {
  338. throw MakeStringException(-1, "CSecureSocket::join_multicast_group: not implemented");
  339. return false;
  340. }
  341. bool leave_multicast_group(SocketEndpoint &ep) // for udp multicast
  342. {
  343. throw MakeStringException(-1, "CSecureSocket::leave_multicast_group: not implemented");
  344. return false;
  345. }
  346. void set_ttl(unsigned _ttl) // set ttl
  347. {
  348. throw MakeStringException(-1, "CSecureSocket::set_ttl: not implemented");
  349. }
  350. size32_t get_receive_buffer_size() // get OS send buffer
  351. {
  352. throw MakeStringException(-1, "CSecureSocket::get_receive_buffer_size: not implemented");
  353. }
  354. void set_receive_buffer_size(size32_t sz) // set OS send buffer size
  355. {
  356. throw MakeStringException(-1, "CSecureSocket::set_receive_buffer_size: not implemented");
  357. }
  358. virtual void set_keep_alive(bool set) // set option SO_KEEPALIVE
  359. {
  360. m_socket->set_keep_alive(set);
  361. }
  362. virtual size32_t udp_write_to(const SocketEndpoint &ep, void const* buf, size32_t size)
  363. {
  364. throw MakeStringException(-1, "CSecureSocket::udp_write_to: not implemented");
  365. }
  366. virtual bool check_connection()
  367. {
  368. return m_socket->check_connection();
  369. }
  370. virtual bool isSecure() const override
  371. {
  372. return m_isSecure;
  373. }
  374. };
  375. #ifdef USERECVSEM
  376. Semaphore CSecureSocket::receiveblocksem(2);
  377. #endif
  378. /**************************************************************************
  379. * CSecureSocket -- secure socket layer implementation using openssl *
  380. **************************************************************************/
  381. CSecureSocket::CSecureSocket(ISocket* sock, SSL_CTX* ctx, bool verify, bool address_match, CStringSet* peers, int loglevel, const char *fqdn)
  382. {
  383. m_socket.setown(sock);
  384. m_ssl = SSL_new(ctx);
  385. m_verify = verify;
  386. m_address_match = address_match;
  387. m_peers = peers;;
  388. m_loglevel = loglevel;
  389. m_isSecure = false;
  390. if(m_ssl == NULL)
  391. {
  392. throw MakeStringException(-1, "Can't create ssl");
  393. }
  394. // there is no MSG_NOSIGNAL or SO_NOSIGPIPE for SSL_write() ...
  395. #ifndef _WIN32
  396. signal(SIGPIPE, SIG_IGN);
  397. #endif
  398. SSL_set_fd(m_ssl, sock->OShandle());
  399. if (fqdn)
  400. m_fqdn.set(fqdn);
  401. }
  402. CSecureSocket::CSecureSocket(int sockfd, SSL_CTX* ctx, bool verify, bool address_match, CStringSet* peers, int loglevel, const char *fqdn)
  403. {
  404. //m_socket.setown(sock);
  405. //m_socket.setown(ISocket::attach(sockfd));
  406. m_ssl = SSL_new(ctx);
  407. m_verify = verify;
  408. m_address_match = address_match;
  409. m_peers = peers;;
  410. m_loglevel = loglevel;
  411. m_isSecure = false;
  412. if(m_ssl == NULL)
  413. {
  414. throw MakeStringException(-1, "Can't create ssl");
  415. }
  416. // there is no MSG_NOSIGNAL or SO_NOSIGPIPE for SSL_write() ...
  417. #ifndef _WIN32
  418. signal(SIGPIPE, SIG_IGN);
  419. #endif
  420. SSL_set_fd(m_ssl, sockfd);
  421. if (fqdn)
  422. m_fqdn.set(fqdn);
  423. }
  424. CSecureSocket::~CSecureSocket()
  425. {
  426. SSL_free(m_ssl);
  427. }
  428. StringBuffer& CSecureSocket::get_cn(X509* cert, StringBuffer& cn)
  429. {
  430. X509_NAME *subj;
  431. char data[256];
  432. int extcount;
  433. int found = 0;
  434. if ((extcount = X509_get_ext_count(cert)) > 0)
  435. {
  436. int i;
  437. for (i = 0; i < extcount; i++)
  438. {
  439. const char *extstr;
  440. X509_EXTENSION *ext;
  441. ext = X509_get_ext(cert, i);
  442. extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
  443. if (!strcmp(extstr, "subjectAltName"))
  444. {
  445. int j;
  446. unsigned char *data;
  447. STACK_OF(CONF_VALUE) *val;
  448. CONF_VALUE *nval;
  449. #if (OPENSSL_VERSION_NUMBER > 0x00909000L)
  450. const X509V3_EXT_METHOD *meth;
  451. #else
  452. X509V3_EXT_METHOD *meth;
  453. #endif
  454. void *ext_str = NULL;
  455. if (!(meth = X509V3_EXT_get(ext)))
  456. break;
  457. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  458. data = ext->value->data;
  459. auto length = ext->value->length;
  460. #else
  461. data = X509_EXTENSION_get_data(ext)->data;
  462. auto length = X509_EXTENSION_get_data(ext)->length;
  463. #endif
  464. #if (OPENSSL_VERSION_NUMBER > 0x00908000L)
  465. if (meth->it)
  466. ext_str = ASN1_item_d2i(NULL, (const unsigned char **)&data, length,
  467. ASN1_ITEM_ptr(meth->it));
  468. else
  469. ext_str = meth->d2i(NULL, (const unsigned char **) &data, length);
  470. #elif (OPENSSL_VERSION_NUMBER > 0x00907000L)
  471. if (meth->it)
  472. ext_str = ASN1_item_d2i(NULL, (unsigned char **)&data, length,
  473. ASN1_ITEM_ptr(meth->it));
  474. else
  475. ext_str = meth->d2i(NULL, (unsigned char **) &data, length);
  476. #else
  477. ext_str = meth->d2i(NULL, &data, length);
  478. #endif
  479. val = meth->i2v(meth, ext_str, NULL);
  480. for (j = 0; j < sk_CONF_VALUE_num(val); j++)
  481. {
  482. nval = sk_CONF_VALUE_value(val, j);
  483. if (!strcmp(nval->name, "DNS"))
  484. {
  485. cn.append(nval->value);
  486. found = 1;
  487. break;
  488. }
  489. }
  490. }
  491. if (found)
  492. break;
  493. }
  494. }
  495. if (!found && (subj = X509_get_subject_name(cert)) &&
  496. X509_NAME_get_text_by_NID(subj, NID_commonName, data, 256) > 0)
  497. {
  498. data[255] = 0;
  499. cn.append(data);
  500. }
  501. return cn;
  502. }
  503. bool CSecureSocket::verify_cert(X509* cert)
  504. {
  505. DBGLOG ("peer's certificate:\n");
  506. char *s, oneline[1024];
  507. s = X509_NAME_oneline (X509_get_subject_name (cert), oneline, 1024);
  508. if(s != NULL)
  509. {
  510. DBGLOG ("\t subject: %s", oneline);
  511. }
  512. s = X509_NAME_oneline (X509_get_issuer_name (cert), oneline, 1024);
  513. if(s != NULL)
  514. {
  515. DBGLOG ("\t issuer: %s", oneline);
  516. }
  517. StringBuffer cn;
  518. get_cn(cert, cn);
  519. if(cn.length() == 0)
  520. throw MakeStringException(-1, "cn of the certificate can't be found");
  521. if(m_address_match)
  522. {
  523. SocketEndpoint ep;
  524. m_socket->getPeerEndpoint(ep);
  525. StringBuffer iptxt;
  526. ep.getIpText(iptxt);
  527. SocketEndpoint cnep(cn.str());
  528. StringBuffer cniptxt;
  529. cnep.getIpText(cniptxt);
  530. DBGLOG("peer ip=%s, certificate ip=%s", iptxt.str(), cniptxt.str());
  531. if(!(cniptxt.length() > 0 && stricmp(iptxt.str(), cniptxt.str()) == 0))
  532. {
  533. DBGLOG("Source address of the request doesn't match the certificate");
  534. return false;
  535. }
  536. }
  537. if (m_peers->contains("anyone") || m_peers->contains(cn.str()))
  538. {
  539. DBGLOG("%s among trusted peers", cn.str());
  540. return true;
  541. }
  542. else
  543. {
  544. DBGLOG("%s not among trusted peers, verification failed", cn.str());
  545. return false;
  546. }
  547. }
  548. int CSecureSocket::secure_accept(int logLevel)
  549. {
  550. int err;
  551. err = SSL_accept(m_ssl);
  552. if(err == 0)
  553. {
  554. int ret = SSL_get_error(m_ssl, err);
  555. // if err == 0 && ret == SSL_ERROR_SYSCALL
  556. // then client closed connection gracefully before ssl neg
  557. // which can happen with port scan / VIP ...
  558. // NOTE: ret could also be SSL_ERROR_ZERO_RETURN if client closed
  559. // gracefully after ssl neg initiated ...
  560. if ( (logLevel >= SSLogNormal) || (ret != SSL_ERROR_SYSCALL) )
  561. {
  562. char errbuf[512];
  563. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  564. DBGLOG("SSL_accept returned 0, error - %s", errbuf);
  565. }
  566. return -1;
  567. }
  568. else if(err < 0)
  569. {
  570. int ret = SSL_get_error(m_ssl, err);
  571. char errbuf[512];
  572. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  573. errbuf[511] = '\0';
  574. DBGLOG("SSL_accept returned %d, SSL_get_error=%d, error - %s", err, ret, errbuf);
  575. if(strstr(errbuf, "error:1408F455:") != NULL)
  576. {
  577. DBGLOG("Unrecoverable SSL library error.");
  578. _exit(0);
  579. }
  580. return err;
  581. }
  582. if (logLevel > SSLogNormal)
  583. DBGLOG("SSL accept ok, using %s", SSL_get_cipher(m_ssl));
  584. if(m_verify)
  585. {
  586. bool verified = false;
  587. // Get client's certificate (note: beware of dynamic allocation) - opt
  588. X509* client_cert = SSL_get_peer_certificate (m_ssl);
  589. if (client_cert != NULL)
  590. {
  591. // We could do all sorts of certificate verification stuff here before
  592. // deallocating the certificate.
  593. verified = verify_cert(client_cert);
  594. X509_free (client_cert);
  595. }
  596. if(!verified)
  597. throw MakeStringException(-1, "certificate verification failed");
  598. }
  599. m_isSecure = true;
  600. return 0;
  601. }
  602. int CSecureSocket::secure_connect(int logLevel)
  603. {
  604. if (m_fqdn.length() > 0)
  605. {
  606. if (!streq(m_fqdn.str(), "."))
  607. SSL_set_tlsext_host_name(m_ssl, m_fqdn.str());
  608. }
  609. int err = SSL_connect (m_ssl);
  610. if(err <= 0)
  611. {
  612. int ret = SSL_get_error(m_ssl, err);
  613. char errbuf[512];
  614. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  615. DBGLOG("SSL_connect error - %s, SSL_get_error=%d, error - %d", errbuf,ret, err);
  616. throw MakeStringException(-1, "SSL_connect failed: %s", errbuf);
  617. }
  618. if (logLevel > SSLogNormal)
  619. DBGLOG("SSL connect ok, using %s", SSL_get_cipher (m_ssl));
  620. // Currently only do fake verify - simply logging the subject and issuer
  621. // The verify parameter makes it possible for the application to verify only
  622. // once per session and cache the result of the verification.
  623. if(m_verify)
  624. {
  625. // Following two steps are optional and not required for
  626. // data exchange to be successful.
  627. // Get server's certificate (note: beware of dynamic allocation) - opt
  628. X509* server_cert = SSL_get_peer_certificate (m_ssl);
  629. bool verified = false;
  630. if(server_cert != NULL)
  631. {
  632. // We could do all sorts of certificate verification stuff here before
  633. // deallocating the certificate.
  634. verified = verify_cert(server_cert);
  635. X509_free (server_cert);
  636. }
  637. if(!verified)
  638. throw MakeStringException(-1, "certificate verification failed");
  639. }
  640. m_isSecure = true;
  641. return 0;
  642. }
  643. //
  644. // log poll() errors
  645. //
  646. int CSecureSocket::logPollError(unsigned revents, const char *rwstr)
  647. {
  648. return m_socket->logPollError(revents, rwstr);
  649. }
  650. //
  651. // This method is called to check whether a socket has data ready
  652. //
  653. int CSecureSocket::wait_read(unsigned timeoutms)
  654. {
  655. int pending = SSL_pending(m_ssl);
  656. if(pending > 0)
  657. return pending;
  658. return m_socket->wait_read(timeoutms);
  659. }
  660. inline unsigned socketTime(bool useSeconds)
  661. {
  662. if (useSeconds)
  663. {
  664. time_t timenow;
  665. return (unsigned) time(&timenow);
  666. }
  667. return msTick();
  668. }
  669. inline unsigned socketTimeRemaining(bool useSeconds, unsigned start, unsigned timeout)
  670. {
  671. unsigned elapsed = socketTime(useSeconds) - start;
  672. if (elapsed < timeout)
  673. {
  674. unsigned timeleft = timeout - elapsed;
  675. if (useSeconds)
  676. timeleft *= 1000;
  677. return timeleft;
  678. }
  679. return 0;
  680. }
  681. void CSecureSocket::readTimeout(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, unsigned timeout, bool useSeconds)
  682. {
  683. size_read = 0;
  684. unsigned start;
  685. unsigned timeleft;
  686. if (timeout != WAIT_FOREVER) {
  687. start = socketTime(useSeconds);
  688. timeleft = timeout;
  689. if (useSeconds)
  690. timeleft *= 1000;
  691. }
  692. do {
  693. int rc;
  694. if (timeout != WAIT_FOREVER) {
  695. rc = wait_read(timeleft);
  696. if (rc < 0) {
  697. THROWSECURESOCKETEXCEPTION("wait_read error");
  698. }
  699. if (rc == 0) {
  700. THROWSECURESOCKETEXCEPTION("timeout expired");
  701. }
  702. timeleft = socketTimeRemaining(useSeconds, start, timeout);
  703. }
  704. ERR_clear_error();
  705. rc = SSL_read(m_ssl, (char*)buf + size_read, max_size - size_read);
  706. if (rc > 0)
  707. {
  708. size_read += rc;
  709. }
  710. else
  711. {
  712. int err = SSL_get_error(m_ssl, rc);
  713. char errbuf[512];
  714. ERR_error_string_n(err, errbuf, 512);
  715. ERR_clear_error();
  716. VStringBuffer errmsg("SSL_read error %d - %s", err, errbuf);
  717. if (m_loglevel >= SSLogMax)
  718. DBGLOG("Warning: %s", errmsg.str());
  719. if (min_size > 0)
  720. throw createJSocketException(JSOCKERR_graceful_close, errmsg);
  721. }
  722. } while (size_read < min_size);
  723. }
  724. void CSecureSocket::readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, unsigned timeoutms)
  725. {
  726. readTimeout(buf, min_size, max_size, size_read, timeoutms, false);
  727. }
  728. void CSecureSocket::read(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read,unsigned timeoutsecs)
  729. {
  730. readTimeout(buf, min_size, max_size, size_read, timeoutsecs, true);
  731. }
  732. size32_t CSecureSocket::write(void const* buf, size32_t size)
  733. {
  734. if (size == 0)
  735. return 0;
  736. int numwritten = SSL_write(m_ssl, buf, size);
  737. // 0 is an error
  738. if (numwritten <= 0)
  739. {
  740. int err = SSL_get_error(m_ssl, numwritten);
  741. // SSL_ERROR_WANT_READ/WRITE errors and retry should not be required
  742. // b/c of blocking bio and SSL_MODE_ENABLE_PARTIAL_WRITE is not set
  743. char errbuf[512];
  744. ERR_error_string_n(err, errbuf, 512);
  745. ERR_clear_error();
  746. VStringBuffer errmsg("SSL_write error %d - %s", err, errbuf);
  747. if (err == SSL_ERROR_ZERO_RETURN)
  748. throw createJSocketException(JSOCKERR_graceful_close, errmsg);
  749. else
  750. throw createJSocketException(JSOCKERR_broken_pipe, errmsg);
  751. }
  752. return numwritten;
  753. }
  754. size32_t CSecureSocket::writetms(void const* buf, size32_t size, unsigned timeoutms)
  755. {
  756. // timeoutms not implemented yet ...
  757. if (size == 0)
  758. return 0;
  759. int numwritten = SSL_write(m_ssl, buf, size);
  760. // 0 is an error
  761. if (numwritten <= 0)
  762. {
  763. int err = SSL_get_error(m_ssl, numwritten);
  764. // SSL_ERROR_WANT_READ/WRITE errors and retry should not be required
  765. // b/c of blocking bio and SSL_MODE_ENABLE_PARTIAL_WRITE is not set
  766. char errbuf[512];
  767. ERR_error_string_n(err, errbuf, 512);
  768. ERR_clear_error();
  769. VStringBuffer errmsg("SSL_write (tms) error %d - %s", err, errbuf);
  770. if (err == SSL_ERROR_ZERO_RETURN)
  771. throw createJSocketException(JSOCKERR_graceful_close, errmsg);
  772. else
  773. throw createJSocketException(JSOCKERR_broken_pipe, errmsg);
  774. }
  775. return numwritten;
  776. }
  777. // ----------------------------
  778. void CSecureSocket::set_block_mode(unsigned flags, size32_t recsize, unsigned _timeoutms)
  779. {
  780. blockflags = flags;
  781. nextblocksize = UINT_MAX;
  782. blocktimeoutms = _timeoutms?_timeoutms:WAIT_FOREVER;
  783. }
  784. size32_t CSecureSocket::receive_block_size()
  785. {
  786. // assumed always paired with receive_block
  787. if (nextblocksize) {
  788. if (blockflags&BF_SYNC_TRANSFER_PULL) {
  789. bool eof=false;
  790. write(&eof,sizeof(eof));
  791. }
  792. size32_t rd;
  793. readtms(&nextblocksize,sizeof(nextblocksize),sizeof(nextblocksize),rd,blocktimeoutms);
  794. _WINREV(nextblocksize);
  795. if (nextblocksize==0) { // confirm eof
  796. try {
  797. bool confirm=true;
  798. write(&confirm,sizeof(confirm));
  799. }
  800. catch (IJSOCK_Exception *e) {
  801. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  802. EXCLOG(e,"receive_block_size");
  803. e->Release();
  804. }
  805. }
  806. else if (blockflags&BF_SYNC_TRANSFER_PUSH) { // leaves receiveblocksem clear
  807. #ifdef USERECVSEM
  808. CSemProtect semprot; // this will catch exception in write
  809. while (!semprot.wait(&receiveblocksem,&receiveblocksemowned,60*1000*5))
  810. IWARNLOG("Receive block stalled");
  811. #endif
  812. bool eof=false;
  813. write(&eof,sizeof(eof));
  814. #ifdef USERECVSEM
  815. semprot.clear();
  816. #endif
  817. }
  818. }
  819. return nextblocksize;
  820. }
  821. size32_t CSecureSocket::receive_block(void *blk, size32_t maxsize)
  822. {
  823. #ifdef USERECVSEM
  824. CSemProtect semprot; // this will catch exceptions
  825. #endif
  826. size32_t sz = nextblocksize;
  827. if (sz) {
  828. if (sz==UINT_MAX) { // need to get size
  829. if (!blk||!maxsize) {
  830. if (blockflags&BF_SYNC_TRANSFER_PUSH) { // ignore block size
  831. size32_t rd;
  832. readtms(&nextblocksize,sizeof(nextblocksize),sizeof(nextblocksize),rd,blocktimeoutms);
  833. }
  834. if (blockflags&(BF_SYNC_TRANSFER_PULL|BF_SYNC_TRANSFER_PUSH)) { // signal eof
  835. bool eof=true;
  836. write(&eof,sizeof(eof));
  837. nextblocksize = 0;
  838. return 0;
  839. }
  840. }
  841. sz = receive_block_size();
  842. if (!sz)
  843. return 0;
  844. }
  845. unsigned startt=usTick(); // include sem block but not initial handshake
  846. #ifdef USERECVSEM
  847. if (blockflags&BF_SYNC_TRANSFER_PUSH) // read_block_size sets semaphore
  848. semprot.set(&receiveblocksem,&receiveblocksemowned); // this will reset semaphore on exit
  849. #endif
  850. nextblocksize = UINT_MAX;
  851. size32_t rd;
  852. if (sz<=maxsize) {
  853. readtms(blk,sz,sz,rd,blocktimeoutms);
  854. }
  855. else { // truncate
  856. readtms(blk,maxsize,maxsize,rd,blocktimeoutms);
  857. sz -= maxsize;
  858. OwnedMalloc<void> tmp = malloc(sz);
  859. readtms(tmp,sz,sz,rd,blocktimeoutms);
  860. sz = maxsize;
  861. }
  862. if (blockflags&BF_RELIABLE_TRANSFER) {
  863. bool isok=true;
  864. write(&isok,sizeof(isok));
  865. }
  866. unsigned elapsed = usTick()-startt;
  867. SSTATS = getSocketStatPtr();
  868. if (SSTATS)
  869. {
  870. SSTATS->blockrecvtime+=elapsed;
  871. SSTATS->numblockrecvs++;
  872. SSTATS->blockrecvsize+=sz;
  873. }
  874. }
  875. return sz;
  876. }
  877. bool CSecureSocket::send_block(const void *blk, size32_t sz)
  878. {
  879. unsigned startt=usTick();
  880. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  881. unsigned startt2 = startt;
  882. unsigned startt3 = startt;
  883. #endif
  884. if (blockflags&BF_SYNC_TRANSFER_PULL) {
  885. size32_t rd;
  886. bool eof = true;
  887. readtms(&eof,sizeof(eof),sizeof(eof),rd,blocktimeoutms);
  888. if (eof)
  889. return false;
  890. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  891. startt2=usTick();
  892. #endif
  893. }
  894. if (!blk||!sz) {
  895. sz = 0;
  896. write(&sz,sizeof(sz));
  897. try {
  898. bool reply;
  899. size32_t rd;
  900. readtms(&reply,sizeof(reply),sizeof(reply),rd,blocktimeoutms);
  901. }
  902. catch (IJSOCK_Exception *e) {
  903. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  904. EXCLOG(e,"CSocket::send_block");
  905. e->Release();
  906. }
  907. return false;
  908. }
  909. size32_t rsz=sz;
  910. _WINREV(rsz);
  911. write(&rsz,sizeof(rsz));
  912. if (blockflags&BF_SYNC_TRANSFER_PUSH) {
  913. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  914. startt2=usTick();
  915. #endif
  916. size32_t rd;
  917. bool eof = true;
  918. readtms(&eof,sizeof(eof),sizeof(eof),rd,blocktimeoutms);
  919. if (eof)
  920. return false;
  921. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  922. startt3=usTick();
  923. #endif
  924. }
  925. write(blk,sz);
  926. if (blockflags&BF_RELIABLE_TRANSFER) {
  927. bool isok=false;
  928. size32_t rd;
  929. readtms(&isok,sizeof(isok),sizeof(isok),rd,blocktimeoutms);
  930. if (!isok)
  931. return false;
  932. }
  933. unsigned nowt = usTick();
  934. unsigned elapsed = nowt-startt;
  935. SSTATS = getSocketStatPtr();
  936. if (SSTATS)
  937. {
  938. SSTATS->blocksendtime+=elapsed;
  939. SSTATS->numblocksends++;
  940. SSTATS->blocksendsize+=sz;
  941. if (elapsed>SSTATS->longestblocksend) {
  942. SSTATS->longestblocksend = elapsed;
  943. SSTATS->longestblocksize = sz;
  944. }
  945. }
  946. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  947. if (elapsed>1000000*60) // over 1min
  948. IWARNLOG("send_block took %ds to %s (%d,%d,%d)",elapsed/1000000,tracename,startt2-startt,startt3-startt2,nowt-startt3);
  949. #endif
  950. return true;
  951. }
  952. // ----------------------------
  953. int verify_callback(int ok, X509_STORE_CTX *store, bool accept_selfsigned)
  954. {
  955. if(!ok)
  956. {
  957. X509 *cert = X509_STORE_CTX_get_current_cert(store);
  958. int err = X509_STORE_CTX_get_error(store);
  959. char issuer[256], subject[256];
  960. X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
  961. X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
  962. if(accept_selfsigned && (stricmp(issuer, subject) == 0))
  963. {
  964. DBGLOG("accepting selfsigned certificate, subject=%s", subject);
  965. ok = true;
  966. }
  967. else
  968. DBGLOG("Error with certificate: issuer=%s,subject=%s,err %d - %s", issuer, subject,err,X509_verify_cert_error_string(err));
  969. }
  970. return ok;
  971. }
  972. int verify_callback_allow_selfSigned(int ok, X509_STORE_CTX *store)
  973. {
  974. return verify_callback(ok, store, true);
  975. }
  976. int verify_callback_reject_selfSigned(int ok, X509_STORE_CTX *store)
  977. {
  978. return verify_callback(ok, store, false);
  979. }
  980. const char* strtok__(const char* s, const char* d, StringBuffer& tok)
  981. {
  982. if(!s || !*s || !d || !*d)
  983. return s;
  984. while(*s && strchr(d, *s))
  985. s++;
  986. while(*s && !strchr(d, *s))
  987. {
  988. tok.append(*s);
  989. s++;
  990. }
  991. return s;
  992. }
  993. class CSecureSocketContext : implements ISecureSocketContext, public CInterface
  994. {
  995. private:
  996. SSL_CTX* m_ctx = nullptr;
  997. #if (OPENSSL_VERSION_NUMBER > 0x00909000L)
  998. const SSL_METHOD* m_meth = nullptr;
  999. #else
  1000. SSL_METHOD* m_meth;
  1001. #endif
  1002. bool m_verify = false;
  1003. bool m_address_match = false;
  1004. Owned<CStringSet> m_peers;
  1005. StringAttr password;
  1006. void setSessionIdContext()
  1007. {
  1008. SSL_CTX_set_session_id_context(m_ctx, (const unsigned char*)"hpccsystems", 11);
  1009. }
  1010. public:
  1011. IMPLEMENT_IINTERFACE;
  1012. CSecureSocketContext(SecureSocketType sockettype)
  1013. {
  1014. m_verify = false;
  1015. m_address_match = false;
  1016. if(sockettype == ClientSocket)
  1017. m_meth = SSLv23_client_method();
  1018. else
  1019. m_meth = SSLv23_server_method();
  1020. m_ctx = SSL_CTX_new(m_meth);
  1021. if(!m_ctx)
  1022. {
  1023. throw MakeStringException(-1, "ctx can't be created");
  1024. }
  1025. if (sockettype == ServerSocket)
  1026. setSessionIdContext();
  1027. SSL_CTX_set_mode(m_ctx, SSL_CTX_get_mode(m_ctx) | SSL_MODE_AUTO_RETRY);
  1028. }
  1029. CSecureSocketContext(const char* certfile, const char* privkeyfile, const char* passphrase, SecureSocketType sockettype)
  1030. {
  1031. m_verify = false;
  1032. m_address_match = false;
  1033. if(sockettype == ClientSocket)
  1034. m_meth = SSLv23_client_method();
  1035. else
  1036. m_meth = SSLv23_server_method();
  1037. m_ctx = SSL_CTX_new(m_meth);
  1038. if(!m_ctx)
  1039. {
  1040. throw MakeStringException(-1, "ctx can't be created");
  1041. }
  1042. if (sockettype == ServerSocket)
  1043. setSessionIdContext();
  1044. password.set(passphrase);
  1045. SSL_CTX_set_default_passwd_cb_userdata(m_ctx, (void*)password.str());
  1046. SSL_CTX_set_default_passwd_cb(m_ctx, pem_passwd_cb);
  1047. if (SSL_CTX_use_certificate_chain_file(m_ctx, certfile)<=0)
  1048. {
  1049. char errbuf[512];
  1050. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1051. throw MakeStringException(-1, "error loading certificate chain file %s - %s", certfile, errbuf);
  1052. }
  1053. if(SSL_CTX_use_PrivateKey_file(m_ctx, privkeyfile, SSL_FILETYPE_PEM) <= 0)
  1054. {
  1055. char errbuf[512];
  1056. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1057. throw MakeStringException(-1, "error loading private key file %s - %s", privkeyfile, errbuf);
  1058. }
  1059. if(!SSL_CTX_check_private_key(m_ctx))
  1060. {
  1061. throw MakeStringException(-1, "Private key does not match the certificate public key");
  1062. }
  1063. SSL_CTX_set_mode(m_ctx, SSL_CTX_get_mode(m_ctx) | SSL_MODE_AUTO_RETRY);
  1064. }
  1065. CSecureSocketContext(const IPropertyTree* config, SecureSocketType sockettype)
  1066. {
  1067. assertex(config);
  1068. m_verify = false;
  1069. m_address_match = false;
  1070. if(sockettype == ClientSocket)
  1071. m_meth = SSLv23_client_method();
  1072. else
  1073. m_meth = SSLv23_server_method();
  1074. m_ctx = SSL_CTX_new(m_meth);
  1075. if(!m_ctx)
  1076. {
  1077. throw MakeStringException(-1, "ctx can't be created");
  1078. }
  1079. if (sockettype == ServerSocket)
  1080. setSessionIdContext();
  1081. const char *cipherList = config->queryProp("cipherList");
  1082. if (!cipherList || !*cipherList)
  1083. cipherList = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5";
  1084. SSL_CTX_set_cipher_list(m_ctx, cipherList);
  1085. const char* passphrase = config->queryProp("passphrase");
  1086. if(passphrase && *passphrase)
  1087. {
  1088. StringBuffer pwd;
  1089. decrypt(pwd, passphrase);
  1090. password.set(pwd);
  1091. SSL_CTX_set_default_passwd_cb_userdata(m_ctx, (void*)password.str());
  1092. SSL_CTX_set_default_passwd_cb(m_ctx, pem_passwd_cb);
  1093. }
  1094. const char* certfile = config->queryProp("certificate");
  1095. if(certfile && *certfile)
  1096. {
  1097. if (SSL_CTX_use_certificate_chain_file(m_ctx, certfile) <= 0)
  1098. {
  1099. char errbuf[512];
  1100. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1101. throw MakeStringException(-1, "error loading certificate chain file %s - %s", certfile, errbuf);
  1102. }
  1103. }
  1104. const char* privkeyfile = config->queryProp("privatekey");
  1105. if(privkeyfile && *privkeyfile)
  1106. {
  1107. if(SSL_CTX_use_PrivateKey_file(m_ctx, privkeyfile, SSL_FILETYPE_PEM) <= 0)
  1108. {
  1109. char errbuf[512];
  1110. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1111. throw MakeStringException(-1, "error loading private key file %s - %s", privkeyfile, errbuf);
  1112. }
  1113. if(!SSL_CTX_check_private_key(m_ctx))
  1114. {
  1115. throw MakeStringException(-1, "Private key does not match the certificate public key");
  1116. }
  1117. }
  1118. SSL_CTX_set_mode(m_ctx, SSL_CTX_get_mode(m_ctx) | SSL_MODE_AUTO_RETRY);
  1119. m_verify = config->getPropBool("verify/@enable");
  1120. m_address_match = config->getPropBool("verify/@address_match");
  1121. if(m_verify)
  1122. {
  1123. const char* capath = config->queryProp("verify/ca_certificates/@path");
  1124. if(capath && *capath)
  1125. {
  1126. if(SSL_CTX_load_verify_locations(m_ctx, capath, NULL) != 1)
  1127. {
  1128. throw MakeStringException(-1, "Error loading CA certificates from %s", capath);
  1129. }
  1130. }
  1131. bool acceptSelfSigned = config->getPropBool("verify/@accept_selfsigned");
  1132. SSL_CTX_set_verify(m_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, (acceptSelfSigned) ? verify_callback_allow_selfSigned : verify_callback_reject_selfSigned);
  1133. m_peers.setown(new CStringSet());
  1134. const char* peersstr = config->queryProp("verify/trusted_peers");
  1135. while(peersstr && *peersstr)
  1136. {
  1137. StringBuffer onepeerbuf;
  1138. peersstr = strtok__(peersstr, "|", onepeerbuf);
  1139. if(onepeerbuf.length() == 0)
  1140. break;
  1141. char* onepeer = onepeerbuf.detach();
  1142. if (isdigit(*onepeer))
  1143. {
  1144. char *dash = strrchr(onepeer, '-');
  1145. if (dash)
  1146. {
  1147. *dash = 0;
  1148. int last = atoi(dash+1);
  1149. char *dot = strrchr(onepeer, '.');
  1150. *dot = 0;
  1151. int first = atoi(dot+1);
  1152. for (int i = first; i <= last; i++)
  1153. {
  1154. StringBuffer t;
  1155. t.append(onepeer).append('.').append(i);
  1156. m_peers->add(t.str());
  1157. }
  1158. }
  1159. else
  1160. {
  1161. m_peers->add(onepeer);
  1162. }
  1163. }
  1164. else
  1165. {
  1166. m_peers->add(onepeer);
  1167. }
  1168. free(onepeer);
  1169. }
  1170. }
  1171. }
  1172. ~CSecureSocketContext()
  1173. {
  1174. SSL_CTX_free(m_ctx);
  1175. }
  1176. ISecureSocket* createSecureSocket(ISocket* sock, int loglevel, const char *fqdn)
  1177. {
  1178. return new CSecureSocket(sock, m_ctx, m_verify, m_address_match, m_peers, loglevel, fqdn);
  1179. }
  1180. ISecureSocket* createSecureSocket(int sockfd, int loglevel, const char *fqdn)
  1181. {
  1182. return new CSecureSocket(sockfd, m_ctx, m_verify, m_address_match, m_peers, loglevel, fqdn);
  1183. }
  1184. };
  1185. class CRsaCertificate : implements ICertificate, public CInterface
  1186. {
  1187. private:
  1188. StringAttr m_destaddr;
  1189. StringAttr m_passphrase;
  1190. int m_days;
  1191. StringAttr m_c;
  1192. StringAttr m_s;
  1193. StringAttr m_l;
  1194. StringAttr m_o;
  1195. StringAttr m_ou;
  1196. StringAttr m_e;
  1197. int m_bits;
  1198. void addNameEntry(X509_NAME *subj, const char* name, const char* value)
  1199. {
  1200. int nid;
  1201. X509_NAME_ENTRY *ent;
  1202. if ((nid = OBJ_txt2nid ((char*)name)) == NID_undef)
  1203. throw MakeStringException(-1, "Error finding NID for %s\n", name);
  1204. if (!(ent = X509_NAME_ENTRY_create_by_NID(NULL, nid, MBSTRING_ASC, (unsigned char*)value, -1)))
  1205. throw MakeStringException(-1, "Error creating Name entry from NID");
  1206. if (X509_NAME_add_entry (subj, ent, -1, 0) != 1)
  1207. throw MakeStringException(-1, "Error adding entry to subject");
  1208. }
  1209. public:
  1210. IMPLEMENT_IINTERFACE;
  1211. CRsaCertificate()
  1212. {
  1213. m_days = 365;
  1214. m_bits = 1024;
  1215. }
  1216. virtual ~CRsaCertificate()
  1217. {
  1218. }
  1219. virtual void setDestAddr(const char* destaddr)
  1220. {
  1221. m_destaddr.set(destaddr);
  1222. }
  1223. virtual void setDays(int days)
  1224. {
  1225. m_days = days;
  1226. }
  1227. virtual void setPassphrase(const char* passphrase)
  1228. {
  1229. m_passphrase.set(passphrase);
  1230. }
  1231. virtual void setCountry(const char* country)
  1232. {
  1233. m_c.set(country);
  1234. }
  1235. virtual void setState(const char* state)
  1236. {
  1237. m_s.set(state);
  1238. }
  1239. virtual void setCity(const char* city)
  1240. {
  1241. m_l.set(city);
  1242. }
  1243. virtual void setOrganization(const char* o)
  1244. {
  1245. m_o.set(o);
  1246. }
  1247. virtual void setOrganizationalUnit(const char* ou)
  1248. {
  1249. m_ou.set(ou);
  1250. }
  1251. virtual void setEmail(const char* email)
  1252. {
  1253. m_e.set(email);
  1254. }
  1255. virtual int generate(StringBuffer& certificate, StringBuffer& privkey)
  1256. {
  1257. if(m_destaddr.length() == 0)
  1258. throw MakeStringException(-1, "Common Name (server's hostname or IP address) not set for certificate");
  1259. if(m_passphrase.length() == 0)
  1260. throw MakeStringException(-1, "passphrase not set.");
  1261. if(m_days <= 0)
  1262. throw MakeStringException(-1, "The number of days should be a positive integer");
  1263. if(m_c.length() == 0)
  1264. m_c.set("US");
  1265. if(m_o.length() == 0)
  1266. m_o.set("Customer Of Seisint");
  1267. BIO *bio_err;
  1268. BIO *pmem, *cmem;
  1269. X509 *x509=NULL;
  1270. EVP_PKEY *pkey=NULL;
  1271. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
  1272. bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
  1273. if ((pkey=EVP_PKEY_new()) == NULL)
  1274. throw MakeStringException(-1, "can't create private key");
  1275. if ((x509=X509_new()) == NULL)
  1276. throw MakeStringException(-1, "can't create X509 structure");
  1277. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1278. RSA *rsa = RSA_generate_key(m_bits, RSA_F4, NULL, NULL);
  1279. #else
  1280. RSA *rsa = RSA_new();
  1281. if (rsa)
  1282. {
  1283. BIGNUM *e;
  1284. e = BN_new();
  1285. if (e)
  1286. {
  1287. BN_set_word(e, RSA_F4);
  1288. RSA_generate_key_ex(rsa, m_bits, e, NULL);
  1289. BN_free(e);
  1290. }
  1291. }
  1292. #endif
  1293. if (!rsa || !EVP_PKEY_assign_RSA(pkey, rsa))
  1294. {
  1295. char errbuf[512];
  1296. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1297. throw MakeStringException(-1, "EVP_PKEY_ASSIGN_RSA error - %s", errbuf);
  1298. }
  1299. X509_NAME *name=NULL;
  1300. X509_set_version(x509,3);
  1301. ASN1_INTEGER_set(X509_get_serialNumber(x509), 0); // serial number set to 0
  1302. X509_gmtime_adj(X509_get_notBefore(x509),0);
  1303. X509_gmtime_adj(X509_get_notAfter(x509),(long)60*60*24*m_days);
  1304. X509_set_pubkey(x509, pkey);
  1305. name=X509_get_subject_name(x509);
  1306. /* This function creates and adds the entry, working out the
  1307. * correct string type and performing checks on its length.
  1308. * Normally we'd check the return value for errors...
  1309. */
  1310. X509_NAME_add_entry_by_txt(name,"C",
  1311. MBSTRING_ASC, (unsigned char*)m_c.get(), -1, -1, 0);
  1312. if(m_s.length() > 0)
  1313. {
  1314. X509_NAME_add_entry_by_txt(name,"S",
  1315. MBSTRING_ASC, (unsigned char*)m_s.get(), -1, -1, 0);
  1316. }
  1317. if(m_l.length() > 0)
  1318. {
  1319. X509_NAME_add_entry_by_txt(name,"L",
  1320. MBSTRING_ASC, (unsigned char*)m_l.get(), -1, -1, 0);
  1321. }
  1322. X509_NAME_add_entry_by_txt(name,"O",
  1323. MBSTRING_ASC, (unsigned char*)m_o.get(), -1, -1, 0);
  1324. if(m_ou.length() > 0)
  1325. {
  1326. X509_NAME_add_entry_by_txt(name,"OU",
  1327. MBSTRING_ASC, (unsigned char*)m_ou.get(), -1, -1, 0);
  1328. }
  1329. if(m_e.length() > 0)
  1330. {
  1331. X509_NAME_add_entry_by_txt(name,"E",
  1332. MBSTRING_ASC, (unsigned char*)m_e.get(), -1, -1, 0);
  1333. }
  1334. X509_NAME_add_entry_by_txt(name,"CN",
  1335. MBSTRING_ASC, (unsigned char*)m_destaddr.get(), -1, -1, 0);
  1336. X509_set_issuer_name(x509,name);
  1337. /* Add extension using V3 code: we can set the config file as NULL
  1338. * because we wont reference any other sections. We can also set
  1339. * the context to NULL because none of these extensions below will need
  1340. * to access it.
  1341. */
  1342. X509_EXTENSION *ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_cert_type, "server");
  1343. if(ex != NULL)
  1344. {
  1345. X509_add_ext(x509, ex, -1);
  1346. X509_EXTENSION_free(ex);
  1347. }
  1348. ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_ssl_server_name,
  1349. (char*)m_destaddr.get());
  1350. if(ex != NULL)
  1351. {
  1352. X509_add_ext(x509, ex,-1);
  1353. X509_EXTENSION_free(ex);
  1354. }
  1355. if (!X509_sign(x509, pkey, EVP_md5()))
  1356. {
  1357. char errbuf[512];
  1358. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1359. throw MakeStringException(-1, "X509_sign error %s", errbuf);
  1360. }
  1361. const EVP_CIPHER *enc = EVP_des_ede3_cbc();
  1362. pmem = BIO_new(BIO_s_mem());
  1363. PEM_write_bio_PrivateKey(pmem, pkey, enc, (unsigned char*)m_passphrase.get(), m_passphrase.length(), NULL, NULL);
  1364. readBio(pmem, privkey);
  1365. cmem = BIO_new(BIO_s_mem());
  1366. PEM_write_bio_X509(cmem, x509);
  1367. readBio(cmem, certificate);
  1368. X509_free(x509);
  1369. EVP_PKEY_free(pkey);
  1370. RSA_free(rsa);
  1371. #ifndef OPENSSL_NO_CRYPTO_MDEBUG
  1372. CRYPTO_mem_leaks(bio_err);
  1373. #endif
  1374. BIO_free(bio_err);
  1375. BIO_free(pmem);
  1376. BIO_free(cmem);
  1377. return 0;
  1378. }
  1379. virtual int generate(StringBuffer& certificate, const char* privkey)
  1380. {
  1381. if(m_destaddr.length() == 0)
  1382. throw MakeStringException(-1, "Common Name (server's hostname or IP address) not set for certificate");
  1383. if(m_passphrase.length() == 0)
  1384. throw MakeStringException(-1, "passphrase not set.");
  1385. if(m_days <= 0)
  1386. throw MakeStringException(-1, "The number of days should be a positive integer");
  1387. if(m_c.length() == 0)
  1388. m_c.set("US");
  1389. if(m_o.length() == 0)
  1390. m_o.set("Customer Of Seisint");
  1391. BIO *bio_err;
  1392. BIO *pmem, *cmem;
  1393. X509 *x509=NULL;
  1394. EVP_PKEY *pkey=NULL;
  1395. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
  1396. bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
  1397. OpenSSL_add_all_algorithms ();
  1398. ERR_load_crypto_strings ();
  1399. pmem = BIO_new(BIO_s_mem());
  1400. BIO_puts(pmem, privkey);
  1401. if (!(pkey = PEM_read_bio_PrivateKey (pmem, NULL, NULL, (void*)m_passphrase.get())))
  1402. throw MakeStringException(-1, "Error reading private key");
  1403. if ((x509=X509_new()) == NULL)
  1404. throw MakeStringException(-1, "can't create X509 structure");
  1405. X509_NAME *name=NULL;
  1406. X509_set_version(x509,3);
  1407. ASN1_INTEGER_set(X509_get_serialNumber(x509), 0); // serial number set to 0
  1408. X509_gmtime_adj(X509_get_notBefore(x509),0);
  1409. X509_gmtime_adj(X509_get_notAfter(x509),(long)60*60*24*m_days);
  1410. X509_set_pubkey(x509, pkey);
  1411. name=X509_get_subject_name(x509);
  1412. /* This function creates and adds the entry, working out the
  1413. * correct string type and performing checks on its length.
  1414. * Normally we'd check the return value for errors...
  1415. */
  1416. X509_NAME_add_entry_by_txt(name,"C",
  1417. MBSTRING_ASC, (unsigned char*)m_c.get(), -1, -1, 0);
  1418. if(m_s.length() > 0)
  1419. {
  1420. X509_NAME_add_entry_by_txt(name,"S",
  1421. MBSTRING_ASC, (unsigned char*)m_s.get(), -1, -1, 0);
  1422. }
  1423. if(m_l.length() > 0)
  1424. {
  1425. X509_NAME_add_entry_by_txt(name,"L",
  1426. MBSTRING_ASC, (unsigned char*)m_l.get(), -1, -1, 0);
  1427. }
  1428. X509_NAME_add_entry_by_txt(name,"O",
  1429. MBSTRING_ASC, (unsigned char*)m_o.get(), -1, -1, 0);
  1430. if(m_ou.length() > 0)
  1431. {
  1432. X509_NAME_add_entry_by_txt(name,"OU",
  1433. MBSTRING_ASC, (unsigned char*)m_ou.get(), -1, -1, 0);
  1434. }
  1435. if(m_e.length() > 0)
  1436. {
  1437. X509_NAME_add_entry_by_txt(name,"E",
  1438. MBSTRING_ASC, (unsigned char*)m_e.get(), -1, -1, 0);
  1439. }
  1440. X509_NAME_add_entry_by_txt(name,"CN",
  1441. MBSTRING_ASC, (unsigned char*)m_destaddr.get(), -1, -1, 0);
  1442. X509_set_issuer_name(x509,name);
  1443. /* Add extension using V3 code: we can set the config file as NULL
  1444. * because we wont reference any other sections. We can also set
  1445. * the context to NULL because none of these extensions below will need
  1446. * to access it.
  1447. */
  1448. X509_EXTENSION *ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_cert_type, "server");
  1449. if(ex != NULL)
  1450. {
  1451. X509_add_ext(x509, ex, -1);
  1452. X509_EXTENSION_free(ex);
  1453. }
  1454. ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_ssl_server_name,
  1455. (char*)m_destaddr.get());
  1456. if(ex != NULL)
  1457. {
  1458. X509_add_ext(x509, ex,-1);
  1459. X509_EXTENSION_free(ex);
  1460. }
  1461. if (!X509_sign(x509, pkey, EVP_md5()))
  1462. {
  1463. char errbuf[512];
  1464. ERR_error_string_n(ERR_get_error(), errbuf, 512);
  1465. throw MakeStringException(-1, "X509_sign error %s", errbuf);
  1466. }
  1467. cmem = BIO_new(BIO_s_mem());
  1468. PEM_write_bio_X509(cmem, x509);
  1469. readBio(cmem, certificate);
  1470. X509_free(x509);
  1471. EVP_PKEY_free(pkey);
  1472. #ifndef OPENSSL_NO_CRYPTO_MDEBUG
  1473. CRYPTO_mem_leaks(bio_err);
  1474. #endif
  1475. BIO_free(bio_err);
  1476. BIO_free(pmem);
  1477. BIO_free(cmem);
  1478. return 0;
  1479. }
  1480. virtual int generateCSR(StringBuffer& privkey, StringBuffer& csr)
  1481. {
  1482. StringBuffer mycert;
  1483. generate(mycert, privkey);
  1484. return generateCSR(privkey.str(), csr);
  1485. }
  1486. virtual int generateCSR(const char* privkey, StringBuffer& csr)
  1487. {
  1488. if(m_destaddr.length() == 0)
  1489. throw MakeStringException(-1, "Common Name (server's hostname or IP address) not set for certificate");
  1490. if(m_passphrase.length() == 0)
  1491. throw MakeStringException(-1, "passphrase not set.");
  1492. if(m_c.length() == 0)
  1493. m_c.set("US");
  1494. if(m_o.length() == 0)
  1495. m_o.set("Customer Of Seisint");
  1496. BIO *bio_err;
  1497. X509_REQ *req;
  1498. X509_NAME *subj;
  1499. EVP_PKEY *pkey = NULL;
  1500. const EVP_MD *digest;
  1501. BIO *pmem;
  1502. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
  1503. bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
  1504. OpenSSL_add_all_algorithms ();
  1505. ERR_load_crypto_strings ();
  1506. pmem = BIO_new(BIO_s_mem());
  1507. BIO_puts(pmem, privkey);
  1508. if (!(pkey = PEM_read_bio_PrivateKey (pmem, NULL, NULL, (void*)m_passphrase.get())))
  1509. throw MakeStringException(-1, "Error reading private key");
  1510. /* create a new request and add the key to it */
  1511. if (!(req = X509_REQ_new ()))
  1512. throw MakeStringException(-1, "Failed to create X509_REQ object");
  1513. X509_REQ_set_version(req,0L);
  1514. X509_REQ_set_pubkey (req, pkey);
  1515. if (!(subj = X509_NAME_new ()))
  1516. throw MakeStringException(-1, "Failed to create X509_NAME object");
  1517. addNameEntry(subj, "countryName", m_c.get());
  1518. if(m_s.length() > 0)
  1519. addNameEntry(subj, "stateOrProvinceName", m_s.get());
  1520. if(m_l.length() > 0)
  1521. addNameEntry(subj, "localityName", m_l.get());
  1522. addNameEntry(subj, "organizationName", m_o.get());
  1523. if(m_ou.length() > 0)
  1524. addNameEntry(subj, "organizationalUnitName", m_ou.get());
  1525. if(m_e.length() > 0)
  1526. addNameEntry(subj, "emailAddress", m_e.get());
  1527. addNameEntry(subj, "commonName", m_destaddr.get());
  1528. if (X509_REQ_set_subject_name (req, subj) != 1)
  1529. throw MakeStringException(-1, "Error adding subject to request");
  1530. /* pick the correct digest and sign the request */
  1531. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1532. auto type = EVP_PKEY_type(pkey->type);
  1533. #else
  1534. auto type = EVP_PKEY_base_id(pkey);
  1535. #endif
  1536. if (type == EVP_PKEY_DSA)
  1537. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1538. digest = EVP_dss1 ();
  1539. #else
  1540. throw MakeStringException(-1, "Error checking public key for a valid digest (DSA not supported by openSSL 1.1)");
  1541. #endif
  1542. else if (type == EVP_PKEY_RSA)
  1543. digest = EVP_sha1 ();
  1544. else
  1545. throw MakeStringException(-1, "Error checking public key for a valid digest");
  1546. if (!(X509_REQ_sign (req, pkey, digest)))
  1547. throw MakeStringException(-1, "Error signing request");
  1548. /* write the completed request */
  1549. BIO* reqmem = BIO_new(BIO_s_mem());
  1550. if (PEM_write_bio_X509_REQ(reqmem, req) != 1)
  1551. throw MakeStringException(-1, "Error while writing request");
  1552. readBio(reqmem, csr);
  1553. #ifndef OPENSSL_NO_CRYPTO_MDEBUG
  1554. CRYPTO_mem_leaks(bio_err);
  1555. #endif
  1556. BIO_free(pmem);
  1557. BIO_free(reqmem);
  1558. EVP_PKEY_free (pkey);
  1559. X509_REQ_free (req);
  1560. return 0;
  1561. }
  1562. };
  1563. } // namespace securesocket
  1564. extern "C" {
  1565. SECURESOCKET_API ISecureSocketContext* createSecureSocketContext(SecureSocketType sockettype)
  1566. {
  1567. return new securesocket::CSecureSocketContext(sockettype);
  1568. }
  1569. SECURESOCKET_API ISecureSocketContext* createSecureSocketContextEx(const char* certfile, const char* privkeyfile, const char* passphrase, SecureSocketType sockettype)
  1570. {
  1571. return new securesocket::CSecureSocketContext(certfile, privkeyfile, passphrase, sockettype);
  1572. }
  1573. SECURESOCKET_API ISecureSocketContext* createSecureSocketContextEx2(const IPropertyTree* config, SecureSocketType sockettype)
  1574. {
  1575. if (config == NULL)
  1576. return createSecureSocketContext(sockettype);
  1577. return new securesocket::CSecureSocketContext(config, sockettype);
  1578. }
  1579. SECURESOCKET_API ISecureSocketContext* createSecureSocketContextSSF(ISmartSocketFactory* ssf)
  1580. {
  1581. if (ssf == nullptr || !ssf->queryTlsConfig())
  1582. return createSecureSocketContext(ClientSocket);
  1583. return new securesocket::CSecureSocketContext(ssf->queryTlsConfig(), ClientSocket);
  1584. }
  1585. SECURESOCKET_API ISecureSocketContext* createSecureSocketContextSecret(const char *mtlsSecretName, SecureSocketType sockettype)
  1586. {
  1587. IPropertyTree *info = queryTlsSecretInfo(mtlsSecretName);
  1588. //if the secret doesn't exist doesn't exist just go on without it. IF it is required the tls connection will fail.
  1589. //This is primarily for client side... server side would probably use the explict ptree config or explict cert param at least for now.
  1590. if (info)
  1591. return createSecureSocketContextEx2(info, sockettype);
  1592. else
  1593. return createSecureSocketContext(sockettype);
  1594. }
  1595. SECURESOCKET_API ISecureSocketContext* createSecureSocketContextSecretSrv(const char *mtlsSecretName)
  1596. {
  1597. if (!queryMtls())
  1598. throw makeStringException(-100, "TLS secure communication requested but not configured");
  1599. IPropertyTree *info = queryTlsSecretInfo(mtlsSecretName);
  1600. if (info)
  1601. return createSecureSocketContextEx2(info, ServerSocket);
  1602. else
  1603. throw makeStringException(-101, "TLS secure communication requested but not configured (2)");
  1604. }
  1605. SECURESOCKET_API ICertificate *createCertificate()
  1606. {
  1607. return new securesocket::CRsaCertificate();
  1608. }
  1609. SECURESOCKET_API int signCertificate(const char* csr, const char* ca_certificate, const char* ca_privkey, const char* ca_passphrase, int days, StringBuffer& certificate)
  1610. {
  1611. EVP_PKEY *pkey, *CApkey;
  1612. const EVP_MD *digest;
  1613. X509 *cert, *CAcert;
  1614. X509_REQ *req;
  1615. X509_NAME *name;
  1616. if(days <= 0)
  1617. days = 365;
  1618. OpenSSL_add_all_algorithms ();
  1619. ERR_load_crypto_strings ();
  1620. BIO *bio_err;
  1621. bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
  1622. // Read in and verify signature on the request
  1623. BIO *csrmem = BIO_new(BIO_s_mem());
  1624. BIO_puts(csrmem, csr);
  1625. if (!(req = PEM_read_bio_X509_REQ(csrmem, NULL, NULL, NULL)))
  1626. throw MakeStringException(-1, "Error reading request from buffer");
  1627. if (!(pkey = X509_REQ_get_pubkey(req)))
  1628. throw MakeStringException(-1, "Error getting public key from request");
  1629. if (X509_REQ_verify (req, pkey) != 1)
  1630. throw MakeStringException(-1, "Error verifying signature on certificate");
  1631. // read in the CA certificate and private key
  1632. BIO *cacertmem = BIO_new(BIO_s_mem());
  1633. BIO_puts(cacertmem, ca_certificate);
  1634. if (!(CAcert = PEM_read_bio_X509(cacertmem, NULL, NULL, NULL)))
  1635. throw MakeStringException(-1, "Error reading CA's certificate from buffer");
  1636. BIO *capkeymem = BIO_new(BIO_s_mem());
  1637. BIO_puts(capkeymem, ca_privkey);
  1638. if (!(CApkey = PEM_read_bio_PrivateKey (capkeymem, NULL, NULL, (void*)ca_passphrase)))
  1639. throw MakeStringException(-1, "Error reading CA private key");
  1640. cert = X509_new();
  1641. X509_set_version(cert,3);
  1642. ASN1_INTEGER_set(X509_get_serialNumber(cert), 0); // serial number set to 0
  1643. // set issuer and subject name of the cert from the req and the CA
  1644. name = X509_REQ_get_subject_name (req);
  1645. X509_set_subject_name (cert, name);
  1646. name = X509_get_subject_name (CAcert);
  1647. X509_set_issuer_name (cert, name);
  1648. //set public key in the certificate
  1649. X509_set_pubkey (cert, pkey);
  1650. // set duration for the certificate
  1651. X509_gmtime_adj (X509_get_notBefore (cert), 0);
  1652. X509_gmtime_adj (X509_get_notAfter (cert), days*24*60*60);
  1653. // sign the certificate with the CA private key
  1654. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1655. auto type = EVP_PKEY_type(CApkey->type);
  1656. #else
  1657. auto type = EVP_PKEY_base_id(CApkey);
  1658. #endif
  1659. if (type == EVP_PKEY_DSA)
  1660. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1661. digest = EVP_dss1 ();
  1662. #else
  1663. throw MakeStringException(-1, "Error checking public key for a valid digest (DSA not supported by openSSL 1.1)");
  1664. #endif
  1665. else if (type == EVP_PKEY_RSA)
  1666. digest = EVP_sha1 ();
  1667. else
  1668. throw MakeStringException(-1, "Error checking public key for a valid digest");
  1669. if (!(X509_sign (cert, CApkey, digest)))
  1670. throw MakeStringException(-1, "Error signing certificate");
  1671. // write the completed certificate
  1672. BIO* cmem = BIO_new(BIO_s_mem());
  1673. PEM_write_bio_X509(cmem, cert);
  1674. readBio(cmem, certificate);
  1675. #ifndef OPENSSL_NO_CRYPTO_MDEBUG
  1676. CRYPTO_mem_leaks(bio_err);
  1677. #endif
  1678. BIO_free(csrmem);
  1679. BIO_free(cacertmem);
  1680. BIO_free(cmem);
  1681. EVP_PKEY_free(pkey);
  1682. X509_REQ_free(req);
  1683. return 0;
  1684. }
  1685. } // extern C
  1686. class CSecureSmartSocketFactory : public CSmartSocketFactory
  1687. {
  1688. public:
  1689. Owned<ISecureSocketContext> secureContext;
  1690. CSecureSmartSocketFactory(const char *_socklist, bool _retry, unsigned _retryInterval, unsigned _dnsInterval) : CSmartSocketFactory(_socklist, _retry, _retryInterval, _dnsInterval)
  1691. {
  1692. secureContext.setown(createSecureSocketContext(ClientSocket));
  1693. }
  1694. CSecureSmartSocketFactory(IPropertyTree &service, bool _retry, unsigned _retryInterval, unsigned _dnsInterval) : CSmartSocketFactory(service, _retry, _retryInterval, _dnsInterval)
  1695. {
  1696. secureContext.setown(createSecureSocketContextEx2(queryTlsConfig(), ClientSocket));
  1697. }
  1698. virtual ISmartSocket *connect_timeout(unsigned timeoutms) override
  1699. {
  1700. SocketEndpoint ep;
  1701. SmartSocketEndpoint *ss = nullptr;
  1702. Owned<ISecureSocket> ssock;
  1703. Owned<ISocket> sock = connect_sock(timeoutms, ss, ep);
  1704. try
  1705. {
  1706. ssock.setown(secureContext->createSecureSocket(sock.getClear()));
  1707. // secure_connect may also DBGLOG() errors ...
  1708. int res = ssock->secure_connect();
  1709. if (res < 0)
  1710. throw MakeStringException(-1, "connect_timeout : Failed to establish secure connection");
  1711. }
  1712. catch (IException *)
  1713. {
  1714. ss->status = false;
  1715. throw;
  1716. }
  1717. return new CSmartSocket(ssock.getClear(), ep, this);
  1718. }
  1719. };
  1720. ISmartSocketFactory *createSecureSmartSocketFactory(const char *_socklist, bool _retry, unsigned _retryInterval, unsigned _dnsInterval)
  1721. {
  1722. return new CSecureSmartSocketFactory(_socklist, _retry, _retryInterval, _dnsInterval);
  1723. }
  1724. ISmartSocketFactory *createSecureSmartSocketFactory(IPropertyTree &service, bool _retry, unsigned _retryInterval, unsigned _dnsInterval)
  1725. {
  1726. return new CSecureSmartSocketFactory(service, _retry, _retryInterval, _dnsInterval);
  1727. }
  1728. class CSingletonSecureSocketConnection: public CSingletonSocketConnection
  1729. {
  1730. public:
  1731. Owned<ISecureSocketContext> secureContextClient;
  1732. Owned<ISecureSocketContext> secureContextServer;
  1733. int tlsLogLevel;
  1734. CSingletonSecureSocketConnection(SocketEndpoint &_ep)
  1735. {
  1736. ep = _ep;
  1737. state = Snone;
  1738. cancelling = false;
  1739. secureContextClient.setown(createSecureSocketContextSecret("local", ClientSocket));
  1740. secureContextServer.setown(createSecureSocketContextSecretSrv("local"));
  1741. #ifdef _CONTAINERIZED
  1742. tlsLogLevel = getComponentConfigSP()->getPropInt("logging/@detail", SSLogMin);
  1743. if (tlsLogLevel >= ExtraneousMsgThreshold) // or InfoMsgThreshold ?
  1744. tlsLogLevel = SSLogMax;
  1745. #else
  1746. tlsLogLevel = SSLogMin;
  1747. #endif
  1748. }
  1749. virtual ~CSingletonSecureSocketConnection()
  1750. {
  1751. try {
  1752. if (sock)
  1753. sock->close();
  1754. }
  1755. catch (IException *e) {
  1756. if (e->errorCode()!=JSOCKERR_graceful_close)
  1757. EXCLOG(e,"CSingletonSocketConnection close");
  1758. e->Release();
  1759. }
  1760. }
  1761. bool connect(unsigned timeoutms) override
  1762. {
  1763. bool srtn = CSingletonSocketConnection::connect(timeoutms);
  1764. if (srtn)
  1765. {
  1766. Owned<ISecureSocket> ssock = secureContextClient->createSecureSocket(sock.getClear(), tlsLogLevel);
  1767. int status = ssock->secure_connect(tlsLogLevel);
  1768. if (status < 0)
  1769. {
  1770. ssock->close();
  1771. return false;
  1772. }
  1773. else
  1774. {
  1775. sock.setown(ssock.getClear());
  1776. return true;
  1777. }
  1778. }
  1779. return srtn;
  1780. }
  1781. bool accept(unsigned timeoutms) override
  1782. {
  1783. bool srtn = CSingletonSocketConnection::accept(timeoutms);
  1784. if (srtn)
  1785. {
  1786. Owned<ISecureSocket> ssock = secureContextServer->createSecureSocket(sock.getClear(), tlsLogLevel);
  1787. int status = ssock->secure_accept(tlsLogLevel);
  1788. if (status < 0)
  1789. {
  1790. ssock->close();
  1791. return false;
  1792. }
  1793. else
  1794. {
  1795. sock.setown(ssock.getClear());
  1796. return true;
  1797. }
  1798. }
  1799. return srtn;
  1800. }
  1801. };
  1802. IConversation *createSingletonSecureSocketConnection(unsigned short port,SocketEndpoint *_ep)
  1803. {
  1804. SocketEndpoint ep;
  1805. if (_ep)
  1806. ep = *_ep;
  1807. if (port)
  1808. ep.port = port;
  1809. return new CSingletonSecureSocketConnection(ep);
  1810. }