securesocket.cpp 48 KB

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