securesocket.cpp 54 KB

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