securesocket.cpp 47 KB

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