securesocket.cpp 66 KB

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