securesocket.cpp 53 KB

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