securesocket.cpp 48 KB

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