2
0

tport_tls.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /*
  2. * This file is part of the Sofia-SIP package
  3. *
  4. * Copyright (C) 2005 Nokia Corporation.
  5. *
  6. * Contact: Pekka Pessi <pekka.pessi@nokia.com>
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public License
  10. * as published by the Free Software Foundation; either version 2.1 of
  11. * the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful, but
  14. * WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with this library; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  21. * 02110-1301 USA
  22. *
  23. */
  24. /**@CFILE tport_tls.c
  25. * @brief TLS interface
  26. *
  27. * @author Mikko Haataja <ext-Mikko.A.Haataja@nokia.com>
  28. * @author Pekka Pessi <ext-Pekka.Pessi@nokia.com>
  29. * @author Jarod Neuner <janeuner@networkharbor.com>
  30. *
  31. */
  32. #include "config.h"
  33. #define OPENSSL_NO_KRB5 oh-no
  34. #define SU_WAKEUP_ARG_T struct tport_s
  35. #include <sofia-sip/su_types.h>
  36. #include <sofia-sip/su.h>
  37. #include <sofia-sip/su_alloc.h>
  38. #include <sofia-sip/su_wait.h>
  39. #include <sofia-sip/su_string.h>
  40. #include <openssl/lhash.h>
  41. #include <openssl/bn.h>
  42. #include <openssl/x509.h>
  43. #include <openssl/x509v3.h>
  44. #include <openssl/ssl.h>
  45. #include <openssl/err.h>
  46. #include <openssl/pem.h>
  47. #include <openssl/rand.h>
  48. #include <openssl/bio.h>
  49. #include <openssl/opensslv.h>
  50. #include <assert.h>
  51. #include <stdio.h>
  52. #include <stdlib.h>
  53. #if HAVE_FUNC
  54. #elif HAVE_FUNCTION
  55. #define __func__ __FUNCTION__
  56. #else
  57. static char const __func__[] = "tport_tls";
  58. #endif
  59. #if HAVE_SIGPIPE
  60. #include <signal.h>
  61. #endif
  62. #if SU_HAVE_PTHREADS
  63. #include <pthread.h>
  64. #if __sun
  65. #undef PTHREAD_ONCE_INIT
  66. #define PTHREAD_ONCE_INIT {{ 0, 0, 0, PTHREAD_ONCE_NOTDONE }}
  67. #endif
  68. static pthread_once_t once = PTHREAD_ONCE_INIT;
  69. #define ONCE_INIT(f) pthread_once(&once, f)
  70. #else
  71. static int once;
  72. #define ONCE_INIT(f) (!once ? (once = 1), f() : (void)0)
  73. #endif
  74. #include "tport_tls.h"
  75. char const tls_version[] = OPENSSL_VERSION_TEXT;
  76. static int tls_ex_data_idx = -1; /* see SSL_get_ex_new_index(3ssl) */
  77. static void
  78. tls_init_once(void)
  79. {
  80. SSL_library_init();
  81. SSL_load_error_strings();
  82. tls_ex_data_idx = SSL_get_ex_new_index(0, "sofia-sip private data", NULL, NULL, NULL);
  83. }
  84. enum { tls_master = 0, tls_slave = 1};
  85. struct tls_s {
  86. su_home_t home[1];
  87. SSL_CTX *ctx;
  88. SSL *con;
  89. BIO *bio_con;
  90. unsigned int type:1,
  91. accept:1,
  92. verify_incoming:1,
  93. verify_outgoing:1,
  94. verify_subj_in:1,
  95. verify_subj_out:1,
  96. verify_date:1,
  97. x509_verified:1;
  98. /* Receiving */
  99. int read_events;
  100. void *read_buffer;
  101. size_t read_buffer_len;
  102. /* Sending */
  103. int write_events;
  104. void *write_buffer;
  105. size_t write_buffer_len;
  106. /* Host names */
  107. su_strlst_t *subjects;
  108. };
  109. enum { tls_buffer_size = 16384 };
  110. /** Log TLS error(s).
  111. *
  112. * Log the TLS error specified by the error code @a e and all the errors in
  113. * the queue. The error code @a e implies no error, and it is not logged.
  114. */
  115. void tls_log_errors(unsigned level, char const *s, unsigned long e)
  116. {
  117. if (e == 0)
  118. e = ERR_get_error();
  119. if (!tport_log->log_init)
  120. su_log_init(tport_log);
  121. if (s == NULL) s = "tls";
  122. for (; e != 0; e = ERR_get_error()) {
  123. if (level <= tport_log->log_level) {
  124. const char *error = ERR_lib_error_string(e);
  125. const char *func = ERR_func_error_string(e);
  126. const char *reason = ERR_reason_error_string(e);
  127. su_llog(tport_log, level, "%s: %08lx:%s:%s:%s\n",
  128. s, e, error, func, reason);
  129. }
  130. }
  131. }
  132. /*
  133. * This callback hands back the password to be used during decryption.
  134. *
  135. * buf : the function will write the password into this buffer
  136. * size : the size of "buf"
  137. * rwflag : indicates whether the callback is being used for reading/
  138. * decryption (0) or writing/encryption (1)
  139. * userdata : pointer tls_issues_t where the passphrase is stored
  140. */
  141. static int passwd_cb(char *buf, int size, int rwflag, void *userdata)
  142. {
  143. if (rwflag == 0) { // reading/decryption
  144. tls_issues_t *tlsi = (tls_issues_t *)userdata;
  145. strncpy(buf, tlsi->passphrase, size);
  146. buf[size - 1] = '\0';
  147. return strlen(tlsi->passphrase);
  148. }
  149. return 0;
  150. }
  151. static
  152. tls_t *tls_create(int type)
  153. {
  154. tls_t *tls = su_home_new(sizeof(*tls));
  155. if (tls)
  156. tls->type = type == tls_master ? tls_master : tls_slave;
  157. return tls;
  158. }
  159. static
  160. void tls_set_default(tls_issues_t *i)
  161. {
  162. i->verify_depth = i->verify_depth == 0 ? 2 : i->verify_depth;
  163. i->cert = i->cert ? i->cert : "agent.pem";
  164. i->key = i->key ? i->key : i->cert;
  165. i->randFile = i->randFile ? i->randFile : "tls_seed.dat";
  166. i->CAfile = i->CAfile ? i->CAfile : "cafile.pem";
  167. i->ciphers = i->ciphers ? i->ciphers : "!eNULL:!aNULL:!EXP:!LOW:!MD5:ALL:@STRENGTH";
  168. /* Default SIP cipher */
  169. /* "RSA-WITH-AES-128-CBC-SHA"; */
  170. /* RFC-2543-compatibility ciphersuite */
  171. /* TLS_RSA_WITH_3DES_EDE_CBC_SHA; */
  172. }
  173. static
  174. int tls_verify_cb(int ok, X509_STORE_CTX *store)
  175. {
  176. if (!ok)
  177. {
  178. char data[256];
  179. X509 *cert = X509_STORE_CTX_get_current_cert(store);
  180. int depth = X509_STORE_CTX_get_error_depth(store);
  181. int err = X509_STORE_CTX_get_error(store);
  182. int sslidx = SSL_get_ex_data_X509_STORE_CTX_idx();
  183. SSL *ssl = X509_STORE_CTX_get_ex_data(store, sslidx);
  184. tls_t *tls = SSL_get_ex_data(ssl, tls_ex_data_idx);
  185. assert(tls);
  186. #define TLS_VERIFY_CB_CLEAR_ERROR(OK,ERR,STORE) \
  187. do {\
  188. OK = 1;\
  189. ERR = X509_V_OK;\
  190. X509_STORE_CTX_set_error(STORE,ERR);\
  191. } while (0)
  192. if (tls->accept && !tls->verify_incoming)
  193. TLS_VERIFY_CB_CLEAR_ERROR(ok, err, store);
  194. else if (!tls->accept && !tls->verify_outgoing)
  195. TLS_VERIFY_CB_CLEAR_ERROR(ok, err, store);
  196. else switch (err) {
  197. case X509_V_ERR_CERT_NOT_YET_VALID:
  198. case X509_V_ERR_CERT_HAS_EXPIRED:
  199. case X509_V_ERR_CRL_NOT_YET_VALID:
  200. case X509_V_ERR_CRL_HAS_EXPIRED:
  201. if (!tls->verify_date)
  202. TLS_VERIFY_CB_CLEAR_ERROR(ok, err, store);
  203. default:
  204. break;
  205. }
  206. if (!ok) {
  207. SU_DEBUG_3(("-Error with certificate at depth: %i\n", depth));
  208. X509_NAME_oneline(X509_get_issuer_name(cert), data, 256);
  209. SU_DEBUG_3((" issuer = %s\n", data));
  210. X509_NAME_oneline(X509_get_subject_name(cert), data, 256);
  211. SU_DEBUG_3((" subject = %s\n", data));
  212. SU_DEBUG_3((" err %i:%s\n", err, X509_verify_cert_error_string(err)));
  213. }
  214. }
  215. return ok;
  216. }
  217. void tls_init(void) {
  218. ONCE_INIT(tls_init_once);
  219. }
  220. #ifndef OPENSSL_NO_EC
  221. static
  222. int tls_init_ecdh_curve(tls_t *tls)
  223. {
  224. #if OPENSSL_VERSION_NUMBER < 0x10002000
  225. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  226. if (!ecdh) {
  227. tls_log_errors(1, "Couldn't create specified curve", 0);
  228. errno = EIO;
  229. return -1;
  230. }
  231. SSL_CTX_set_options(tls->ctx, SSL_OP_SINGLE_ECDH_USE);
  232. SSL_CTX_set_tmp_ecdh(tls->ctx, ecdh);
  233. EC_KEY_free(ecdh);
  234. return 0;
  235. #elif OPENSSL_VERSION_NUMBER < 0x10100000
  236. if (!SSL_CTX_set_ecdh_auto(tls->ctx, 1)) {
  237. return -1;
  238. }
  239. SSL_CTX_set_options(tls->ctx, SSL_OP_SINGLE_ECDH_USE);
  240. return 0;
  241. #else
  242. return 0;
  243. #endif
  244. }
  245. #endif
  246. static
  247. int tls_init_context(tls_t *tls, tls_issues_t const *ti)
  248. {
  249. int verify;
  250. static int random_loaded;
  251. ONCE_INIT(tls_init_once);
  252. if (!random_loaded) {
  253. random_loaded = 1;
  254. if (ti->randFile &&
  255. !RAND_load_file(ti->randFile, 1024 * 1024)) {
  256. if (ti->configured > 1) {
  257. SU_DEBUG_3(("%s: cannot open randFile %s\n",
  258. "tls_init_context", ti->randFile));
  259. tls_log_errors(3, "tls_init_context", 0);
  260. }
  261. /* errno = EIO; */
  262. /* return -1; */
  263. }
  264. }
  265. #if HAVE_SIGPIPE
  266. /* Avoid possible SIGPIPE when sending close_notify */
  267. signal(SIGPIPE, SIG_IGN);
  268. #endif
  269. if (tls->ctx == NULL)
  270. if (!(tls->ctx = SSL_CTX_new((SSL_METHOD*)SSLv23_method()))) {
  271. tls_log_errors(1, "SSL_CTX_new() failed", 0);
  272. errno = EIO;
  273. return -1;
  274. }
  275. if (!(ti->version & TPTLS_VERSION_SSLv2))
  276. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_SSLv2);
  277. if (!(ti->version & TPTLS_VERSION_SSLv3))
  278. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_SSLv3);
  279. if (!(ti->version & TPTLS_VERSION_TLSv1))
  280. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_TLSv1);
  281. if (!(ti->version & TPTLS_VERSION_TLSv1_1))
  282. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_TLSv1_1);
  283. if (!(ti->version & TPTLS_VERSION_TLSv1_2))
  284. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_TLSv1_2);
  285. SSL_CTX_sess_set_remove_cb(tls->ctx, NULL);
  286. SSL_CTX_set_timeout(tls->ctx, ti->timeout);
  287. /* CRIME (CVE-2012-4929) mitigation */
  288. SSL_CTX_set_options(tls->ctx, SSL_OP_NO_COMPRESSION);
  289. /* Set callback if we have a passphrase */
  290. if (ti->passphrase != NULL) {
  291. SSL_CTX_set_default_passwd_cb(tls->ctx, passwd_cb);
  292. SSL_CTX_set_default_passwd_cb_userdata(tls->ctx, (void *)ti);
  293. }
  294. if (!SSL_CTX_use_certificate_file(tls->ctx,
  295. ti->cert,
  296. SSL_FILETYPE_PEM)) {
  297. if (ti->configured > 0) {
  298. SU_DEBUG_1(("%s: invalid local certificate: %s\n",
  299. "tls_init_context", ti->cert));
  300. tls_log_errors(3, "tls_init_context", 0);
  301. #if require_client_certificate
  302. errno = EIO;
  303. return -1;
  304. #endif
  305. }
  306. }
  307. if (!SSL_CTX_use_PrivateKey_file(tls->ctx,
  308. ti->key,
  309. SSL_FILETYPE_PEM)) {
  310. if (ti->configured > 0) {
  311. SU_DEBUG_1(("%s: invalid private key: %s\n",
  312. "tls_init_context", ti->key));
  313. tls_log_errors(3, "tls_init_context(key)", 0);
  314. #if require_client_certificate
  315. errno = EIO;
  316. return -1;
  317. #endif
  318. }
  319. }
  320. if (!SSL_CTX_check_private_key(tls->ctx)) {
  321. if (ti->configured > 0) {
  322. SU_DEBUG_1(("%s: private key does not match the certificate public key\n",
  323. "tls_init_context"));
  324. }
  325. #if require_client_certificate
  326. errno = EIO;
  327. return -1;
  328. #endif
  329. #ifndef OPENSSL_NO_DH
  330. } else {
  331. BIO *bio = BIO_new_file(ti->key, "r");
  332. if (bio != NULL) {
  333. DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  334. if (dh != NULL) {
  335. if (!SSL_CTX_set_tmp_dh(tls->ctx, dh)) {
  336. SU_DEBUG_1(("%s: invalid DH parameters (PFS) because %s: %s\n",
  337. "tls_init_context",
  338. ERR_reason_error_string(ERR_get_error()),
  339. ti->key));
  340. } else {
  341. long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE;
  342. SSL_CTX_set_options(tls->ctx, options);
  343. SU_DEBUG_3(("%s\n", "tls: initialized DHE"));
  344. }
  345. DH_free(dh);
  346. }
  347. BIO_free(bio);
  348. }
  349. #endif
  350. }
  351. if (!SSL_CTX_load_verify_locations(tls->ctx,
  352. ti->CAfile,
  353. ti->CApath)) {
  354. SU_DEBUG_1(("%s: error loading CA list: %s\n",
  355. "tls_init_context", ti->CAfile));
  356. if (ti->configured > 0)
  357. tls_log_errors(3, "tls_init_context(CA)", 0);
  358. errno = EIO;
  359. return -1;
  360. }
  361. /* corresponds to (enum tport_tls_verify_policy) */
  362. tls->verify_incoming = (ti->policy & 0x1) ? 1 : 0;
  363. tls->verify_outgoing = (ti->policy & 0x2) ? 1 : 0;
  364. tls->verify_subj_in = (ti->policy & 0x4) ? tls->verify_incoming : 0;
  365. tls->verify_subj_out = (ti->policy & 0x8) ? tls->verify_outgoing : 0;
  366. tls->verify_date = (ti->verify_date) ? 1 : 0;
  367. if (tls->verify_incoming)
  368. verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  369. else
  370. verify = SSL_VERIFY_NONE;
  371. SSL_CTX_set_verify_depth(tls->ctx, ti->verify_depth);
  372. SSL_CTX_set_verify(tls->ctx, verify, tls_verify_cb);
  373. #ifndef OPENSSL_NO_EC
  374. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  375. if (tls_init_ecdh_curve(tls) == 0) {
  376. SU_DEBUG_3(("%s\n", "tls: initialized ECDH"));
  377. } else {
  378. SU_DEBUG_3(("%s\n", "tls: failed to initialize ECDH"));
  379. }
  380. #else
  381. if (tls->accept == 0) {
  382. SU_DEBUG_3(("%s\n", "tls: initialized ECDH"));
  383. } else if (tls_init_ecdh_curve(tls) == 0) {
  384. SU_DEBUG_3(("%s\n", "tls: initialized ECDH"));
  385. } else {
  386. SU_DEBUG_3(("%s\n", "tls: failed to initialize ECDH"));
  387. }
  388. #endif
  389. #endif
  390. if (!SSL_CTX_set_cipher_list(tls->ctx, ti->ciphers)) {
  391. SU_DEBUG_1(("%s: error setting cipher list\n", "tls_init_context"));
  392. tls_log_errors(3, "tls_init_context", 0);
  393. errno = EIO;
  394. return -1;
  395. }
  396. return 0;
  397. }
  398. void tls_free(tls_t *tls)
  399. {
  400. int ret;
  401. if (!tls)
  402. return;
  403. if (tls->con != NULL) {
  404. do {
  405. ret = SSL_shutdown(tls->con);
  406. if (ret == -1) {
  407. /* The return value -1 means that the connection wasn't actually established */
  408. /* so it should be safe to not call shutdown again. We need to clear the eror */
  409. /* queue for other connections though. */
  410. tls_log_errors(3, "tls_free", 0);
  411. ret = 1;
  412. }
  413. } while (ret != 1);
  414. SSL_free(tls->con), tls->con = NULL;
  415. }
  416. if (tls->ctx != NULL && tls->type != tls_slave) {
  417. SSL_CTX_free(tls->ctx);
  418. }
  419. su_home_unref(tls->home);
  420. }
  421. int tls_get_socket(tls_t *tls)
  422. {
  423. int sock = -1;
  424. if (tls != NULL && tls->bio_con != NULL)
  425. BIO_get_fd(tls->bio_con, &sock);
  426. return sock;
  427. }
  428. tls_t *tls_init_master(tls_issues_t *ti)
  429. {
  430. /* Default id in case RAND fails */
  431. unsigned char sessionId[32] = "sofia/tls";
  432. tls_t *tls;
  433. #if HAVE_SIGPIPE
  434. signal(SIGPIPE, SIG_IGN); /* Ignore spurios SIGPIPE from OpenSSL */
  435. #endif
  436. tls_set_default(ti);
  437. if (!(tls = tls_create(tls_master)))
  438. return NULL;
  439. if (tls_init_context(tls, ti) < 0) {
  440. int err = errno;
  441. tls_free(tls);
  442. errno = err;
  443. return NULL;
  444. }
  445. RAND_bytes(sessionId, sizeof(sessionId));
  446. if (!SSL_CTX_set_session_id_context(tls->ctx,
  447. (void*) sessionId,
  448. sizeof(sessionId))) {
  449. tls_log_errors(3, "tls_init_master", 0);
  450. }
  451. if (ti->CAfile != NULL) {
  452. SSL_CTX_set_client_CA_list(tls->ctx,
  453. SSL_load_client_CA_file(ti->CAfile));
  454. #if OPENSSL_VERSION_NUMBER >= 0x10100000
  455. if (SSL_CTX_get_client_CA_list(tls->ctx) == NULL)
  456. #else
  457. if (tls->ctx->client_CA == NULL)
  458. #endif
  459. tls_log_errors(3, "tls_init_master", 0);
  460. }
  461. #if 0
  462. if (sock != -1) {
  463. tls->bio_con = BIO_new_socket(sock, BIO_NOCLOSE);
  464. if (tls->bio_con == NULL) {
  465. tls_log_errors(1, "tls_init_master", 0);
  466. tls_free(tls);
  467. errno = EIO;
  468. return NULL;
  469. }
  470. }
  471. #endif
  472. return tls;
  473. }
  474. tls_t *tls_init_secondary(tls_t *master, int sock, int accept)
  475. {
  476. tls_t *tls = tls_create(tls_slave);
  477. if (tls) {
  478. tls->ctx = master->ctx;
  479. tls->accept = accept ? 1 : 0;
  480. tls->verify_outgoing = master->verify_outgoing;
  481. tls->verify_incoming = master->verify_incoming;
  482. tls->verify_subj_out = master->verify_subj_out;
  483. tls->verify_subj_in = master->verify_subj_in;
  484. tls->verify_date = master->verify_date;
  485. tls->x509_verified = master->x509_verified;
  486. if (!(tls->read_buffer = su_alloc(tls->home, tls_buffer_size)))
  487. su_home_unref(tls->home), tls = NULL;
  488. }
  489. if (!tls)
  490. return tls;
  491. assert(sock != -1);
  492. tls->bio_con = BIO_new_socket(sock, BIO_NOCLOSE);
  493. tls->con = SSL_new(tls->ctx);
  494. if (tls->con == NULL) {
  495. tls_log_errors(1, "tls_init_secondary", 0);
  496. tls_free(tls);
  497. errno = EIO;
  498. return NULL;
  499. }
  500. SSL_set_bio(tls->con, tls->bio_con, tls->bio_con);
  501. SSL_set_mode(tls->con, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  502. SSL_set_ex_data(tls->con, tls_ex_data_idx, tls);
  503. su_setblocking(sock, 0);
  504. return tls;
  505. }
  506. su_inline
  507. int tls_post_connection_check(tport_t *self, tls_t *tls)
  508. {
  509. X509 *cert;
  510. const SSL_CIPHER *cipher;
  511. char cipher_description[256];
  512. int cipher_bits, alg_bits;
  513. int extcount;
  514. int i, j, error;
  515. if (!tls) return -1;
  516. if (!(cipher = SSL_get_current_cipher(tls->con))) {
  517. tls_log_errors(3, "tls_post_connection_check", 0);
  518. SU_DEBUG_7(("%s(%p): %s\n", __func__, (void*)self,
  519. "OpenSSL failed to return an SSL_CIPHER object to us."));
  520. return SSL_ERROR_SSL;
  521. }
  522. SU_DEBUG_9(("%s(%p): TLS cipher chosen (name): %s\n", __func__, (void*)self,
  523. SSL_CIPHER_get_name(cipher)));
  524. SU_DEBUG_9(("%s(%p): TLS cipher chosen (version): %s\n", __func__, (void*)self,
  525. SSL_CIPHER_get_version(cipher)));
  526. cipher_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
  527. SU_DEBUG_9(("%s(%p): TLS cipher chosen (bits/alg_bits): %d/%d\n", __func__, (void*)self,
  528. cipher_bits, alg_bits));
  529. SSL_CIPHER_description(cipher, cipher_description, sizeof(cipher_description));
  530. SU_DEBUG_9(("%s(%p): TLS cipher chosen (description): %s\n", __func__, (void*)self,
  531. cipher_description));
  532. cert = SSL_get_peer_certificate(tls->con);
  533. if (!cert) {
  534. SU_DEBUG_7(("%s(%p): Peer did not provide X.509 Certificate.\n",
  535. __func__, (void *) self));
  536. if (self->tp_accepted && tls->verify_incoming)
  537. return X509_V_ERR_CERT_UNTRUSTED;
  538. else if (!self->tp_accepted && tls->verify_outgoing)
  539. return X509_V_ERR_CERT_UNTRUSTED;
  540. else
  541. return X509_V_OK;
  542. }
  543. tls->subjects = su_strlst_create(tls->home);
  544. if (!tls->subjects)
  545. return X509_V_ERR_OUT_OF_MEM;
  546. extcount = X509_get_ext_count(cert);
  547. /* Find matching subjectAltName.DNS */
  548. for (i = 0; i < extcount; i++) {
  549. X509_EXTENSION *ext;
  550. char const *name;
  551. #if OPENSSL_VERSION_NUMBER > 0x10000000L
  552. const X509V3_EXT_METHOD *vp;
  553. #else
  554. X509V3_EXT_METHOD *vp;
  555. #endif
  556. STACK_OF(CONF_VALUE) *values;
  557. CONF_VALUE *value;
  558. void *d2i;
  559. ext = X509_get_ext(cert, i);
  560. name = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
  561. if (strcmp(name, "subjectAltName") != 0)
  562. continue;
  563. vp = X509V3_EXT_get(ext); if (!vp) continue;
  564. d2i = X509V3_EXT_d2i(ext);
  565. values = vp->i2v(vp, d2i, NULL);
  566. for (j = 0; j < sk_CONF_VALUE_num(values); j++) {
  567. value = sk_CONF_VALUE_value(values, j);
  568. if (strcmp(value->name, "DNS") == 0)
  569. su_strlst_dup_append(tls->subjects, value->value);
  570. if (strcmp(value->name, "IP") == 0)
  571. su_strlst_dup_append(tls->subjects, value->value);
  572. else if (strcmp(value->name, "URI") == 0)
  573. su_strlst_dup_append(tls->subjects, value->value);
  574. }
  575. }
  576. {
  577. X509_NAME *subject;
  578. char name[256];
  579. subject = X509_get_subject_name(cert);
  580. if (subject) {
  581. if (X509_NAME_get_text_by_NID(subject, NID_commonName,
  582. name, sizeof name) > 0) {
  583. usize_t k, N = su_strlst_len(tls->subjects);
  584. name[(sizeof name) - 1] = '\0';
  585. for (k = 0; k < N; k++)
  586. if (su_casematch(su_strlst_item(tls->subjects, k), name) == 0)
  587. break;
  588. if (k >= N)
  589. su_strlst_dup_append(tls->subjects, name);
  590. }
  591. }
  592. }
  593. X509_free(cert);
  594. error = SSL_get_verify_result(tls->con);
  595. if (cert && error == X509_V_OK)
  596. tls->x509_verified = 1;
  597. if (tport_log->log_level >= 7) {
  598. int i, len = su_strlst_len(tls->subjects);
  599. for (i=0; i < len; i++)
  600. SU_DEBUG_7(("%s(%p): Peer Certificate Subject %i: %s\n", \
  601. __func__, (void *)self, i, su_strlst_item(tls->subjects, i)));
  602. if (i == 0)
  603. SU_DEBUG_7(("%s(%p): Peer Certificate provided no usable subjects.\n",
  604. __func__, (void *)self));
  605. }
  606. /* Verify incoming connections */
  607. if (self->tp_accepted) {
  608. if (!tls->verify_incoming)
  609. return X509_V_OK;
  610. if (!tls->x509_verified)
  611. return error;
  612. if (tls->verify_subj_in) {
  613. su_strlst_t const *subjects = self->tp_pri->pri_primary->tp_subjects;
  614. int i, items;
  615. items = subjects ? su_strlst_len(subjects) : 0;
  616. if (items == 0)
  617. return X509_V_OK;
  618. for (i=0; i < items; i++) {
  619. if (tport_subject_search(su_strlst_item(subjects, i), tls->subjects))
  620. return X509_V_OK;
  621. }
  622. SU_DEBUG_3(("%s(%p): Peer Subject Mismatch (incoming connection)\n", \
  623. __func__, (void *)self));
  624. return X509_V_ERR_CERT_UNTRUSTED;
  625. }
  626. }
  627. /* Verify outgoing connections */
  628. else {
  629. char const *subject = self->tp_canon;
  630. if (!tls->verify_outgoing)
  631. return X509_V_OK;
  632. if (!tls->x509_verified || !subject)
  633. return error;
  634. if (tls->verify_subj_out) {
  635. if (tport_subject_search(subject, tls->subjects))
  636. return X509_V_OK; /* Subject match found in verified certificate chain */
  637. SU_DEBUG_3(("%s(%p): Peer Subject Mismatch (%s)\n", \
  638. __func__, (void *)self, subject));
  639. return X509_V_ERR_CERT_UNTRUSTED;
  640. }
  641. }
  642. return error;
  643. }
  644. static
  645. int tls_error(tls_t *tls, int ret, char const *who,
  646. void *buf, int size)
  647. {
  648. int events = 0;
  649. int err = SSL_get_error(tls->con, ret);
  650. switch (err) {
  651. case SSL_ERROR_WANT_WRITE:
  652. events = SU_WAIT_OUT;
  653. break;
  654. case SSL_ERROR_WANT_READ:
  655. events = SU_WAIT_IN;
  656. break;
  657. case SSL_ERROR_ZERO_RETURN:
  658. return 0;
  659. case SSL_ERROR_SYSCALL:
  660. ERR_clear_error();
  661. if (SSL_get_shutdown(tls->con) & SSL_RECEIVED_SHUTDOWN)
  662. return 0; /* EOS */
  663. if (errno == 0)
  664. return 0; /* EOS */
  665. return -1;
  666. default:
  667. tls_log_errors(1, who, err);
  668. errno = EIO;
  669. return -1;
  670. }
  671. if (buf) {
  672. tls->write_events = events;
  673. tls->write_buffer = buf, tls->write_buffer_len = size;
  674. }
  675. else {
  676. tls->read_events = events;
  677. }
  678. errno = EAGAIN;
  679. return -1;
  680. }
  681. ssize_t tls_read(tls_t *tls)
  682. {
  683. ssize_t ret;
  684. if (tls == NULL) {
  685. errno = EINVAL;
  686. return -1;
  687. }
  688. if (0)
  689. SU_DEBUG_1(("tls_read(%p) called on %s (events %u)\n", (void *)tls,
  690. tls->type ? "master" : "slave",
  691. tls->read_events));
  692. if (tls->read_buffer_len)
  693. return (ssize_t)tls->read_buffer_len;
  694. tls->read_events = SU_WAIT_IN;
  695. ret = SSL_read(tls->con, tls->read_buffer, tls_buffer_size);
  696. if (ret <= 0)
  697. return tls_error(tls, ret, "tls_read: SSL_read", NULL, 0);
  698. return (ssize_t)(tls->read_buffer_len = ret);
  699. }
  700. void *tls_read_buffer(tls_t *tls, size_t N)
  701. {
  702. assert(N == tls->read_buffer_len);
  703. tls->read_buffer_len = 0;
  704. return tls->read_buffer;
  705. }
  706. int tls_pending(tls_t const *tls)
  707. {
  708. return tls && tls->con && SSL_pending(tls->con);
  709. }
  710. /** Check if data is available in TCP connection.
  711. *
  712. *
  713. *
  714. * @retval -1 upon an error
  715. * @retval 0 end-of-stream
  716. * @retval 1 nothing to read
  717. * @retval 2 there is data to read
  718. */
  719. int tls_want_read(tls_t *tls, int events)
  720. {
  721. if (tls && (events & tls->read_events)) {
  722. int ret = tls_read(tls);
  723. if (ret > 0)
  724. return 2;
  725. else if (ret == 0)
  726. return 0;
  727. else if (errno == EAGAIN)
  728. return 3; /* ??? */
  729. else
  730. return -1;
  731. }
  732. return 1;
  733. }
  734. ssize_t tls_write(tls_t *tls, void *buf, size_t size)
  735. {
  736. ssize_t ret;
  737. if (0)
  738. SU_DEBUG_1(("tls_write(%p, %p, "MOD_ZU") called on %s\n",
  739. (void *)tls, buf, size,
  740. tls && tls->type == tls_slave ? "master" : "slave"));
  741. if (tls == NULL || buf == NULL) {
  742. errno = EINVAL;
  743. return -1;
  744. }
  745. if (tls->write_buffer) {
  746. assert(buf == tls->write_buffer);
  747. assert(size >= tls->write_buffer_len);
  748. assert(tls->write_events == 0);
  749. if (tls->write_events ||
  750. buf != tls->write_buffer ||
  751. size < tls->write_buffer_len) {
  752. errno = EIO;
  753. return -1;
  754. }
  755. ret = tls->write_buffer_len;
  756. tls->write_buffer = NULL;
  757. tls->write_buffer_len = 0;
  758. return ret;
  759. }
  760. if (size == 0)
  761. return 0;
  762. tls->write_events = 0;
  763. ret = SSL_write(tls->con, buf, size);
  764. if (ret <= 0)
  765. return tls_error(tls, ret, "tls_write: SSL_write", buf, size);
  766. return ret;
  767. }
  768. int tls_want_write(tls_t *tls, int events)
  769. {
  770. if (tls && (events & tls->write_events)) {
  771. int ret;
  772. void *buf = tls->write_buffer;
  773. size_t size = tls->write_buffer_len;
  774. tls->write_events = 0;
  775. /* remove buf */
  776. tls->write_buffer = NULL;
  777. tls->write_buffer_len = 0;
  778. ret = tls_write(tls, buf, size);
  779. if (ret >= 0)
  780. /* Restore buf */
  781. return tls->write_buffer = buf, tls->write_buffer_len = ret;
  782. else if (errno == EAGAIN)
  783. return 0;
  784. else
  785. return -1;
  786. }
  787. return 0;
  788. }
  789. int tls_events(tls_t const *tls, int mask)
  790. {
  791. if (!tls)
  792. return mask;
  793. if (tls->type == tls_master)
  794. return mask;
  795. return
  796. (mask & ~(SU_WAIT_IN|SU_WAIT_OUT)) |
  797. ((mask & SU_WAIT_IN) ? tls->read_events : 0) |
  798. ((mask & SU_WAIT_OUT) ? tls->write_events : 0);
  799. }
  800. int tls_connect(su_root_magic_t *magic, su_wait_t *w, tport_t *self)
  801. {
  802. tport_master_t *mr = self->tp_master;
  803. tport_tls_t *tlstp = (tport_tls_t *)self;
  804. tls_t *tls;
  805. int events = su_wait_events(w, self->tp_socket);
  806. int error;
  807. SU_DEBUG_7(("%s(%p): events%s%s%s%s\n", __func__, (void *)self,
  808. events & (SU_WAIT_CONNECT) ? " CONNECTING" : "",
  809. events & SU_WAIT_IN ? " NEGOTIATING" : "",
  810. events & SU_WAIT_ERR ? " ERROR" : "",
  811. events & SU_WAIT_HUP ? " HANGUP" : ""));
  812. #if HAVE_POLL
  813. assert(w->fd == self->tp_socket);
  814. #endif
  815. if (events & SU_WAIT_ERR)
  816. tport_error_event(self);
  817. if (events & SU_WAIT_HUP && !self->tp_closed)
  818. tport_hup_event(self);
  819. if (self->tp_closed) {
  820. SU_DEBUG_9(("%s(%p): tport was closed during connect. Returning, but set secondary timer first.\n",
  821. __func__, (void *)self));
  822. tport_set_secondary_timer(self);
  823. return 0;
  824. }
  825. error = su_soerror(self->tp_socket);
  826. if (error) {
  827. tport_error_report(self, error, NULL);
  828. SU_DEBUG_9(("%s(%p): socket error during connect. Returning, but set secondary timer first.\n",
  829. __func__, (void *)self));
  830. tport_set_secondary_timer(self);
  831. return 0;
  832. }
  833. if ((tls = tlstp->tlstp_context) == NULL) {
  834. SU_DEBUG_3(("%s(%p): Error: no TLS context data for connected socket.\n",
  835. __func__, (void *)tlstp));
  836. tport_close(self);
  837. tport_set_secondary_timer(self);
  838. return 0;
  839. }
  840. if (self->tp_is_connected == 0) {
  841. int ret, status;
  842. ret = self->tp_accepted ? SSL_accept(tls->con) : SSL_connect(tls->con);
  843. status = SSL_get_error(tls->con, ret);
  844. switch (status) {
  845. case SSL_ERROR_WANT_READ:
  846. /* OpenSSL is waiting for the peer to send handshake data */
  847. self->tp_events = SU_WAIT_IN | SU_WAIT_ERR | SU_WAIT_HUP;
  848. su_root_eventmask(mr->mr_root, self->tp_index,
  849. self->tp_socket, self->tp_events);
  850. return 0;
  851. case SSL_ERROR_WANT_WRITE:
  852. /* OpenSSL is waiting for the peer to receive handshake data */
  853. self->tp_events = SU_WAIT_IN | SU_WAIT_ERR | SU_WAIT_HUP | SU_WAIT_OUT;
  854. su_root_eventmask(mr->mr_root, self->tp_index,
  855. self->tp_socket, self->tp_events);
  856. return 0;
  857. case SSL_ERROR_NONE:
  858. /* TLS Handshake complete */
  859. status = tls_post_connection_check(self, tls);
  860. if ( status == X509_V_OK ) {
  861. su_wait_t wait[1] = {SU_WAIT_INIT};
  862. tport_master_t *mr = self->tp_master;
  863. int su_wait_create_ret;
  864. su_root_deregister(mr->mr_root, self->tp_index);
  865. self->tp_index = -1;
  866. self->tp_events = SU_WAIT_IN | SU_WAIT_ERR | SU_WAIT_HUP;
  867. if (((su_wait_create_ret = su_wait_create(wait, self->tp_socket, self->tp_events)) == -1) ||
  868. ((self->tp_index = su_root_register(mr->mr_root, wait, tport_wakeup,
  869. self, 0)) == -1)) {
  870. if (su_wait_create_ret == 0) {
  871. su_wait_destroy(wait);
  872. }
  873. tls_log_errors(3, "TLS post handshake error", status);
  874. tport_close(self);
  875. tport_set_secondary_timer(self);
  876. return 0;
  877. }
  878. tls->read_events = SU_WAIT_IN;
  879. tls->write_events = 0;
  880. self->tp_is_connected = 1;
  881. self->tp_verified = tls->x509_verified;
  882. self->tp_subjects = tls->subjects;
  883. if (tport_has_queued(self))
  884. tport_send_event(self);
  885. else
  886. tport_set_secondary_timer(self);
  887. return 0;
  888. }
  889. break;
  890. default:
  891. tls_log_errors(3, "TLS setup failed", status);
  892. break;
  893. }
  894. }
  895. /* TLS Handshake Failed or Peer Certificate did not Verify */
  896. tport_close(self);
  897. tport_set_secondary_timer(self);
  898. return 0;
  899. }