securesocket.cpp 52 KB

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