tortls.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file tortls.c
  7. * \brief Wrapper functions to present a consistent interface to
  8. * TLS, SSL, and X.509 functions from OpenSSL.
  9. **/
  10. /* (Unlike other tor functions, these
  11. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  12. * functions and variables.)
  13. */
  14. #include "orconfig.h"
  15. #if defined (WINCE)
  16. #include <WinSock2.h>
  17. #endif
  18. #include <assert.h>
  19. #ifdef MS_WINDOWS /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  20. #ifndef WIN32_WINNT
  21. #define WIN32_WINNT 0x400
  22. #endif
  23. #ifndef _WIN32_WINNT
  24. #define _WIN32_WINNT 0x400
  25. #endif
  26. #define WIN32_LEAN_AND_MEAN
  27. #if defined(_MSC_VER) && (_MSC_VER < 1300)
  28. #include <winsock.h>
  29. #else
  30. #include <winsock2.h>
  31. #include <ws2tcpip.h>
  32. #endif
  33. #endif
  34. #include <openssl/ssl.h>
  35. #include <openssl/ssl3.h>
  36. #include <openssl/err.h>
  37. #include <openssl/tls1.h>
  38. #include <openssl/asn1.h>
  39. #include <openssl/bio.h>
  40. #include <openssl/opensslv.h>
  41. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  42. #error "We require OpenSSL >= 0.9.7"
  43. #endif
  44. #ifdef USE_BUFFEREVENTS
  45. #include <event2/bufferevent_ssl.h>
  46. #include <event2/buffer.h>
  47. #include "compat_libevent.h"
  48. #endif
  49. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  50. #define TORTLS_PRIVATE
  51. #include "crypto.h"
  52. #include "tortls.h"
  53. #include "util.h"
  54. #include "torlog.h"
  55. #include "container.h"
  56. #include <string.h>
  57. /* Enable the "v2" TLS handshake.
  58. */
  59. #define V2_HANDSHAKE_SERVER
  60. #define V2_HANDSHAKE_CLIENT
  61. /* Copied from or.h */
  62. #define LEGAL_NICKNAME_CHARACTERS \
  63. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  64. /** How long do identity certificates live? (sec) */
  65. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  66. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  67. /* We redefine these so that we can run correctly even if the vendor gives us
  68. * a version of OpenSSL that does not match its header files. (Apple: I am
  69. * looking at you.)
  70. */
  71. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  72. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  73. #endif
  74. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  75. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  76. #endif
  77. /** Does the run-time openssl version look like we need
  78. * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  79. static int use_unsafe_renegotiation_op = 0;
  80. /** Does the run-time openssl version look like we need
  81. * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  82. static int use_unsafe_renegotiation_flag = 0;
  83. /** Holds a SSL_CTX object and related state used to configure TLS
  84. * connections.
  85. */
  86. typedef struct tor_tls_context_t {
  87. int refcnt;
  88. SSL_CTX *ctx;
  89. X509 *my_cert;
  90. X509 *my_id_cert;
  91. crypto_pk_env_t *key;
  92. } tor_tls_context_t;
  93. #define TOR_TLS_MAGIC 0x71571571
  94. /** Holds a SSL object and its associated data. Members are only
  95. * accessed from within tortls.c.
  96. */
  97. struct tor_tls_t {
  98. uint32_t magic;
  99. tor_tls_context_t *context; /** A link to the context object for this tls. */
  100. SSL *ssl; /**< An OpenSSL SSL object. */
  101. int socket; /**< The underlying file descriptor for this TLS connection. */
  102. char *address; /**< An address to log when describing this connection. */
  103. enum {
  104. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  105. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  106. TOR_TLS_ST_BUFFEREVENT
  107. } state : 3; /**< The current SSL state, depending on which operations have
  108. * completed successfully. */
  109. unsigned int isServer:1; /**< True iff this is a server-side connection */
  110. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  111. * this connection used the updated version
  112. * of the connection protocol (client sends
  113. * different cipher list, server sends only
  114. * one certificate). */
  115. /** True iff we should call negotiated_callback when we're done reading. */
  116. unsigned int got_renegotiate:1;
  117. /** Incremented every time we start the server side of a handshake. */
  118. uint8_t server_handshake_count;
  119. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  120. * time. */
  121. /** Last values retrieved from BIO_number_read()/write(); see
  122. * tor_tls_get_n_raw_bytes() for usage.
  123. */
  124. unsigned long last_write_count;
  125. unsigned long last_read_count;
  126. /** If set, a callback to invoke whenever the client tries to renegotiate
  127. * the handshake. */
  128. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  129. /** Argument to pass to negotiated_callback. */
  130. void *callback_arg;
  131. };
  132. #ifdef V2_HANDSHAKE_CLIENT
  133. /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
  134. * in client mode into advertising the ciphers we want. See
  135. * rectify_client_ciphers() for details. */
  136. static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
  137. /** A stack of SSL_CIPHER objects, some real, some fake.
  138. * See rectify_client_ciphers() for details. */
  139. static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
  140. #endif
  141. /** The ex_data index in which we store a pointer to an SSL object's
  142. * corresponding tor_tls_t object. */
  143. static int tor_tls_object_ex_data_index = -1;
  144. /** Helper: Allocate tor_tls_object_ex_data_index. */
  145. static void
  146. tor_tls_allocate_tor_tls_object_ex_data_index(void)
  147. {
  148. if (tor_tls_object_ex_data_index == -1) {
  149. tor_tls_object_ex_data_index =
  150. SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  151. tor_assert(tor_tls_object_ex_data_index != -1);
  152. }
  153. }
  154. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  155. * pointer. */
  156. static INLINE tor_tls_t *
  157. tor_tls_get_by_ssl(const SSL *ssl)
  158. {
  159. tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  160. if (result)
  161. tor_assert(result->magic == TOR_TLS_MAGIC);
  162. return result;
  163. }
  164. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  165. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  166. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  167. crypto_pk_env_t *rsa_sign,
  168. const char *cname,
  169. const char *cname_sign,
  170. unsigned int lifetime);
  171. static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  172. crypto_pk_env_t *identity,
  173. unsigned int key_lifetime);
  174. static tor_tls_context_t *tor_tls_context_new(crypto_pk_env_t *identity,
  175. unsigned int key_lifetime);
  176. /** Global TLS contexts. We keep them here because nobody else needs
  177. * to touch them. */
  178. static tor_tls_context_t *server_tls_context = NULL;
  179. static tor_tls_context_t *client_tls_context = NULL;
  180. /** True iff tor_tls_init() has been called. */
  181. static int tls_library_is_initialized = 0;
  182. /* Module-internal error codes. */
  183. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  184. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  185. #include "tortls_states.h"
  186. /** Return the symbolic name of an OpenSSL state. */
  187. static const char *
  188. ssl_state_to_string(int ssl_state)
  189. {
  190. static char buf[40];
  191. int i;
  192. for (i = 0; state_map[i].name; ++i) {
  193. if (state_map[i].state == ssl_state)
  194. return state_map[i].name;
  195. }
  196. tor_snprintf(buf, sizeof(buf), "Unknown state %d", ssl_state);
  197. return buf;
  198. }
  199. /** Write a description of the current state of <b>tls</b> into the
  200. * <b>sz</b>-byte buffer at <b>buf</b>. */
  201. void
  202. tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
  203. {
  204. const char *ssl_state;
  205. const char *tortls_state;
  206. if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
  207. strlcpy(buf, "(No SSL object)", sz);
  208. return;
  209. }
  210. ssl_state = ssl_state_to_string(tls->ssl->state);
  211. switch (tls->state) {
  212. #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
  213. CASE(HANDSHAKE);
  214. CASE(OPEN);
  215. CASE(GOTCLOSE);
  216. CASE(SENTCLOSE);
  217. CASE(CLOSED);
  218. CASE(RENEGOTIATE);
  219. #undef CASE
  220. case TOR_TLS_ST_BUFFEREVENT:
  221. tortls_state = "";
  222. break;
  223. default:
  224. tortls_state = " in unknown TLS state";
  225. break;
  226. }
  227. tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
  228. }
  229. void
  230. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  231. int severity, int domain, const char *doing)
  232. {
  233. const char *state = NULL, *addr;
  234. const char *msg, *lib, *func;
  235. int st;
  236. st = (tls && tls->ssl) ? tls->ssl->state : -1;
  237. state = (st>=0)?ssl_state_to_string(st):"---";
  238. addr = tls ? tls->address : NULL;
  239. msg = (const char*)ERR_reason_error_string(err);
  240. lib = (const char*)ERR_lib_error_string(err);
  241. func = (const char*)ERR_func_error_string(err);
  242. if (!msg) msg = "(null)";
  243. if (!lib) lib = "(null)";
  244. if (!func) func = "(null)";
  245. if (doing) {
  246. log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  247. doing, addr?" with ":"", addr?addr:"",
  248. msg, lib, func, state);
  249. } else {
  250. log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  251. addr?" with ":"", addr?addr:"",
  252. msg, lib, func, state);
  253. }
  254. }
  255. /** Log all pending tls errors at level <b>severity</b>. Use
  256. * <b>doing</b> to describe our current activities.
  257. */
  258. static void
  259. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  260. {
  261. unsigned long err;
  262. while ((err = ERR_get_error()) != 0) {
  263. tor_tls_log_one_error(tls, err, severity, domain, doing);
  264. }
  265. }
  266. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  267. * code. */
  268. static int
  269. tor_errno_to_tls_error(int e)
  270. {
  271. #if defined(MS_WINDOWS)
  272. switch (e) {
  273. case WSAECONNRESET: // most common
  274. return TOR_TLS_ERROR_CONNRESET;
  275. case WSAETIMEDOUT:
  276. return TOR_TLS_ERROR_TIMEOUT;
  277. case WSAENETUNREACH:
  278. case WSAEHOSTUNREACH:
  279. return TOR_TLS_ERROR_NO_ROUTE;
  280. case WSAECONNREFUSED:
  281. return TOR_TLS_ERROR_CONNREFUSED; // least common
  282. default:
  283. return TOR_TLS_ERROR_MISC;
  284. }
  285. #else
  286. switch (e) {
  287. case ECONNRESET: // most common
  288. return TOR_TLS_ERROR_CONNRESET;
  289. case ETIMEDOUT:
  290. return TOR_TLS_ERROR_TIMEOUT;
  291. case EHOSTUNREACH:
  292. case ENETUNREACH:
  293. return TOR_TLS_ERROR_NO_ROUTE;
  294. case ECONNREFUSED:
  295. return TOR_TLS_ERROR_CONNREFUSED; // least common
  296. default:
  297. return TOR_TLS_ERROR_MISC;
  298. }
  299. #endif
  300. }
  301. /** Given a TOR_TLS_* error code, return a string equivalent. */
  302. const char *
  303. tor_tls_err_to_string(int err)
  304. {
  305. if (err >= 0)
  306. return "[Not an error.]";
  307. switch (err) {
  308. case TOR_TLS_ERROR_MISC: return "misc error";
  309. case TOR_TLS_ERROR_IO: return "unexpected close";
  310. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  311. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  312. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  313. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  314. case TOR_TLS_CLOSE: return "closed";
  315. case TOR_TLS_WANTREAD: return "want to read";
  316. case TOR_TLS_WANTWRITE: return "want to write";
  317. default: return "(unknown error code)";
  318. }
  319. }
  320. #define CATCH_SYSCALL 1
  321. #define CATCH_ZERO 2
  322. /** Given a TLS object and the result of an SSL_* call, use
  323. * SSL_get_error to determine whether an error has occurred, and if so
  324. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  325. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  326. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  327. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  328. *
  329. * If an error has occurred, log it at level <b>severity</b> and describe the
  330. * current action as <b>doing</b>.
  331. */
  332. static int
  333. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  334. const char *doing, int severity, int domain)
  335. {
  336. int err = SSL_get_error(tls->ssl, r);
  337. int tor_error = TOR_TLS_ERROR_MISC;
  338. switch (err) {
  339. case SSL_ERROR_NONE:
  340. return TOR_TLS_DONE;
  341. case SSL_ERROR_WANT_READ:
  342. return TOR_TLS_WANTREAD;
  343. case SSL_ERROR_WANT_WRITE:
  344. return TOR_TLS_WANTWRITE;
  345. case SSL_ERROR_SYSCALL:
  346. if (extra&CATCH_SYSCALL)
  347. return _TOR_TLS_SYSCALL;
  348. if (r == 0) {
  349. log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  350. doing, ssl_state_to_string(tls->ssl->state));
  351. tor_error = TOR_TLS_ERROR_IO;
  352. } else {
  353. int e = tor_socket_errno(tls->socket);
  354. log(severity, LD_NET,
  355. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  356. doing, e, tor_socket_strerror(e),
  357. ssl_state_to_string(tls->ssl->state));
  358. tor_error = tor_errno_to_tls_error(e);
  359. }
  360. tls_log_errors(tls, severity, domain, doing);
  361. return tor_error;
  362. case SSL_ERROR_ZERO_RETURN:
  363. if (extra&CATCH_ZERO)
  364. return _TOR_TLS_ZERORETURN;
  365. log(severity, LD_NET, "TLS connection closed while %s in state %s",
  366. doing, ssl_state_to_string(tls->ssl->state));
  367. tls_log_errors(tls, severity, domain, doing);
  368. return TOR_TLS_CLOSE;
  369. default:
  370. tls_log_errors(tls, severity, domain, doing);
  371. return TOR_TLS_ERROR_MISC;
  372. }
  373. }
  374. /** Initialize OpenSSL, unless it has already been initialized.
  375. */
  376. static void
  377. tor_tls_init(void)
  378. {
  379. if (!tls_library_is_initialized) {
  380. long version;
  381. SSL_library_init();
  382. SSL_load_error_strings();
  383. version = SSLeay();
  384. /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  385. * here, but without thinking too hard about it: it turns out that the
  386. * flag in question needed to be set at the last minute, and that it
  387. * conflicted with an existing flag number that had already been added
  388. * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
  389. * the flag with an option and (it seems) broke anything that used
  390. * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
  391. * and we mustn't use the SSL3_FLAGS option with anything besides
  392. * OpenSSL 0.9.8l.
  393. *
  394. * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
  395. * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
  396. * set option 0x00040000L everywhere.
  397. *
  398. * No, we can't simply detect whether the flag or the option is present
  399. * in the headers at build-time: some vendors (notably Apple) like to
  400. * leave their headers out of sync with their libraries.
  401. *
  402. * Yes, it _is_ almost as if the OpenSSL developers decided that no
  403. * program should be allowed to use renegotiation unless it first passed
  404. * a test of intelligence and determination.
  405. */
  406. if (version >= 0x009080c0L && version < 0x009080d0L) {
  407. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
  408. "I will try SSL3_FLAGS to enable renegotation.",
  409. SSLeay_version(SSLEAY_VERSION));
  410. use_unsafe_renegotiation_flag = 1;
  411. use_unsafe_renegotiation_op = 1;
  412. } else if (version >= 0x009080d0L) {
  413. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
  414. "I will try SSL_OP to enable renegotiation",
  415. SSLeay_version(SSLEAY_VERSION));
  416. use_unsafe_renegotiation_op = 1;
  417. } else if (version < 0x009080c0L) {
  418. log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
  419. "0.9.8l, but some vendors have backported 0.9.8l's "
  420. "renegotiation code to earlier versions, and some have "
  421. "backported the code from 0.9.8m or 0.9.8n. I'll set both "
  422. "SSL3_FLAGS and SSL_OP just to be safe.",
  423. SSLeay_version(SSLEAY_VERSION), version);
  424. use_unsafe_renegotiation_flag = 1;
  425. use_unsafe_renegotiation_op = 1;
  426. } else {
  427. log_info(LD_GENERAL, "OpenSSL %s has version %lx",
  428. SSLeay_version(SSLEAY_VERSION), version);
  429. }
  430. tor_tls_allocate_tor_tls_object_ex_data_index();
  431. tls_library_is_initialized = 1;
  432. }
  433. }
  434. /** Free all global TLS structures. */
  435. void
  436. tor_tls_free_all(void)
  437. {
  438. if (server_tls_context) {
  439. tor_tls_context_t *ctx = server_tls_context;
  440. server_tls_context = NULL;
  441. tor_tls_context_decref(ctx);
  442. }
  443. if (client_tls_context) {
  444. tor_tls_context_t *ctx = client_tls_context;
  445. client_tls_context = NULL;
  446. tor_tls_context_decref(ctx);
  447. }
  448. #ifdef V2_HANDSHAKE_CLIENT
  449. if (CLIENT_CIPHER_DUMMIES)
  450. tor_free(CLIENT_CIPHER_DUMMIES);
  451. if (CLIENT_CIPHER_STACK)
  452. sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
  453. #endif
  454. }
  455. /** We need to give OpenSSL a callback to verify certificates. This is
  456. * it: We always accept peer certs and complete the handshake. We
  457. * don't validate them until later.
  458. */
  459. static int
  460. always_accept_verify_cb(int preverify_ok,
  461. X509_STORE_CTX *x509_ctx)
  462. {
  463. (void) preverify_ok;
  464. (void) x509_ctx;
  465. return 1;
  466. }
  467. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  468. static X509_NAME *
  469. tor_x509_name_new(const char *cname)
  470. {
  471. int nid;
  472. X509_NAME *name;
  473. if (!(name = X509_NAME_new()))
  474. return NULL;
  475. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  476. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  477. (unsigned char*)cname, -1, -1, 0)))
  478. goto error;
  479. return name;
  480. error:
  481. X509_NAME_free(name);
  482. return NULL;
  483. }
  484. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  485. * signed by the private key <b>rsa_sign</b>. The commonName of the
  486. * certificate will be <b>cname</b>; the commonName of the issuer will be
  487. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  488. * starting from now. Return a certificate on success, NULL on
  489. * failure.
  490. */
  491. static X509 *
  492. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  493. crypto_pk_env_t *rsa_sign,
  494. const char *cname,
  495. const char *cname_sign,
  496. unsigned int cert_lifetime)
  497. {
  498. time_t start_time, end_time;
  499. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  500. X509 *x509 = NULL;
  501. X509_NAME *name = NULL, *name_issuer=NULL;
  502. tor_tls_init();
  503. start_time = time(NULL);
  504. tor_assert(rsa);
  505. tor_assert(cname);
  506. tor_assert(rsa_sign);
  507. tor_assert(cname_sign);
  508. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  509. goto error;
  510. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  511. goto error;
  512. if (!(x509 = X509_new()))
  513. goto error;
  514. if (!(X509_set_version(x509, 2)))
  515. goto error;
  516. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  517. goto error;
  518. if (!(name = tor_x509_name_new(cname)))
  519. goto error;
  520. if (!(X509_set_subject_name(x509, name)))
  521. goto error;
  522. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  523. goto error;
  524. if (!(X509_set_issuer_name(x509, name_issuer)))
  525. goto error;
  526. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  527. goto error;
  528. end_time = start_time + cert_lifetime;
  529. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  530. goto error;
  531. if (!X509_set_pubkey(x509, pkey))
  532. goto error;
  533. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  534. goto error;
  535. goto done;
  536. error:
  537. if (x509) {
  538. X509_free(x509);
  539. x509 = NULL;
  540. }
  541. done:
  542. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  543. if (sign_pkey)
  544. EVP_PKEY_free(sign_pkey);
  545. if (pkey)
  546. EVP_PKEY_free(pkey);
  547. if (name)
  548. X509_NAME_free(name);
  549. if (name_issuer)
  550. X509_NAME_free(name_issuer);
  551. return x509;
  552. }
  553. /** List of ciphers that servers should select from.*/
  554. #define SERVER_CIPHER_LIST \
  555. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  556. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  557. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  558. /* Note: to set up your own private testing network with link crypto
  559. * disabled, set your Tors' cipher list to
  560. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  561. * with any of the "real" Tors, though. */
  562. #ifdef V2_HANDSHAKE_CLIENT
  563. #define CIPHER(id, name) name ":"
  564. #define XCIPHER(id, name)
  565. /** List of ciphers that clients should advertise, omitting items that
  566. * our OpenSSL doesn't know about. */
  567. static const char CLIENT_CIPHER_LIST[] =
  568. #include "./ciphers.inc"
  569. ;
  570. #undef CIPHER
  571. #undef XCIPHER
  572. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  573. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  574. /** A list of all the ciphers that clients should advertise, including items
  575. * that OpenSSL might not know about. */
  576. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  577. #define CIPHER(id, name) { id, name },
  578. #define XCIPHER(id, name) { id, #name },
  579. #include "./ciphers.inc"
  580. #undef CIPHER
  581. #undef XCIPHER
  582. };
  583. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  584. static const int N_CLIENT_CIPHERS =
  585. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  586. #endif
  587. #ifndef V2_HANDSHAKE_CLIENT
  588. #undef CLIENT_CIPHER_LIST
  589. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  590. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  591. #endif
  592. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  593. * references. */
  594. static void
  595. tor_tls_context_decref(tor_tls_context_t *ctx)
  596. {
  597. tor_assert(ctx);
  598. if (--ctx->refcnt == 0) {
  599. SSL_CTX_free(ctx->ctx);
  600. X509_free(ctx->my_cert);
  601. X509_free(ctx->my_id_cert);
  602. crypto_free_pk_env(ctx->key);
  603. tor_free(ctx);
  604. }
  605. }
  606. /** Increase the reference count of <b>ctx</b>. */
  607. static void
  608. tor_tls_context_incref(tor_tls_context_t *ctx)
  609. {
  610. ++ctx->refcnt;
  611. }
  612. /** Create new global client and server TLS contexts.
  613. *
  614. * If <b>server_identity</b> is NULL, this will not generate a server
  615. * TLS context. If <b>is_public_server</b> is non-zero, this will use
  616. * the same TLS context for incoming and outgoing connections, and
  617. * ignore <b>client_identity</b>. */
  618. int
  619. tor_tls_context_init(int is_public_server,
  620. crypto_pk_env_t *client_identity,
  621. crypto_pk_env_t *server_identity,
  622. unsigned int key_lifetime)
  623. {
  624. int rv1 = 0;
  625. int rv2 = 0;
  626. if (is_public_server) {
  627. tor_tls_context_t *new_ctx;
  628. tor_tls_context_t *old_ctx;
  629. tor_assert(server_identity != NULL);
  630. rv1 = tor_tls_context_init_one(&server_tls_context,
  631. server_identity,
  632. key_lifetime);
  633. if (rv1 >= 0) {
  634. new_ctx = server_tls_context;
  635. tor_tls_context_incref(new_ctx);
  636. old_ctx = client_tls_context;
  637. client_tls_context = new_ctx;
  638. if (old_ctx != NULL) {
  639. tor_tls_context_decref(old_ctx);
  640. }
  641. }
  642. } else {
  643. if (server_identity != NULL) {
  644. rv1 = tor_tls_context_init_one(&server_tls_context,
  645. server_identity,
  646. key_lifetime);
  647. } else {
  648. tor_tls_context_t *old_ctx = server_tls_context;
  649. server_tls_context = NULL;
  650. if (old_ctx != NULL) {
  651. tor_tls_context_decref(old_ctx);
  652. }
  653. }
  654. rv2 = tor_tls_context_init_one(&client_tls_context,
  655. client_identity,
  656. key_lifetime);
  657. }
  658. return MIN(rv1, rv2);
  659. }
  660. /** Create a new global TLS context.
  661. *
  662. * You can call this function multiple times. Each time you call it,
  663. * it generates new certificates; all new connections will use
  664. * the new SSL context.
  665. */
  666. static int
  667. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  668. crypto_pk_env_t *identity,
  669. unsigned int key_lifetime)
  670. {
  671. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  672. key_lifetime);
  673. tor_tls_context_t *old_ctx = *ppcontext;
  674. if (new_ctx != NULL) {
  675. *ppcontext = new_ctx;
  676. /* Free the old context if one existed. */
  677. if (old_ctx != NULL) {
  678. /* This is safe even if there are open connections: we reference-
  679. * count tor_tls_context_t objects. */
  680. tor_tls_context_decref(old_ctx);
  681. }
  682. }
  683. return ((new_ctx != NULL) ? 0 : -1);
  684. }
  685. /** Create a new TLS context for use with Tor TLS handshakes.
  686. * <b>identity</b> should be set to the identity key used to sign the
  687. * certificate.
  688. */
  689. static tor_tls_context_t *
  690. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
  691. {
  692. crypto_pk_env_t *rsa = NULL;
  693. EVP_PKEY *pkey = NULL;
  694. tor_tls_context_t *result = NULL;
  695. X509 *cert = NULL, *idcert = NULL;
  696. char *nickname = NULL, *nn2 = NULL;
  697. tor_tls_init();
  698. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  699. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  700. /* Generate short-term RSA key. */
  701. if (!(rsa = crypto_new_pk_env()))
  702. goto error;
  703. if (crypto_pk_generate_key(rsa)<0)
  704. goto error;
  705. /* Create certificate signed by identity key. */
  706. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  707. key_lifetime);
  708. /* Create self-signed certificate for identity key. */
  709. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  710. IDENTITY_CERT_LIFETIME);
  711. if (!cert || !idcert) {
  712. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  713. goto error;
  714. }
  715. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  716. result->refcnt = 1;
  717. result->my_cert = X509_dup(cert);
  718. result->my_id_cert = X509_dup(idcert);
  719. result->key = crypto_pk_dup_key(rsa);
  720. #ifdef EVERYONE_HAS_AES
  721. /* Tell OpenSSL to only use TLS1 */
  722. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  723. goto error;
  724. #else
  725. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  726. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  727. goto error;
  728. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  729. #endif
  730. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  731. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  732. SSL_CTX_set_options(result->ctx,
  733. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  734. #endif
  735. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  736. * as authenticating any earlier-received data.
  737. */
  738. if (use_unsafe_renegotiation_op) {
  739. SSL_CTX_set_options(result->ctx,
  740. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  741. }
  742. /* Don't actually allow compression; it uses ram and time, but the data
  743. * we transmit is all encrypted anyway. */
  744. if (result->ctx->comp_methods)
  745. result->ctx->comp_methods = NULL;
  746. #ifdef SSL_MODE_RELEASE_BUFFERS
  747. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  748. #endif
  749. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  750. goto error;
  751. X509_free(cert); /* We just added a reference to cert. */
  752. cert=NULL;
  753. if (idcert) {
  754. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  755. tor_assert(s);
  756. X509_STORE_add_cert(s, idcert);
  757. X509_free(idcert); /* The context now owns the reference to idcert */
  758. idcert = NULL;
  759. }
  760. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  761. tor_assert(rsa);
  762. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  763. goto error;
  764. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  765. goto error;
  766. EVP_PKEY_free(pkey);
  767. pkey = NULL;
  768. if (!SSL_CTX_check_private_key(result->ctx))
  769. goto error;
  770. {
  771. crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS);
  772. tor_assert(dh);
  773. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  774. crypto_dh_free(dh);
  775. }
  776. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  777. always_accept_verify_cb);
  778. /* let us realloc bufs that we're writing from */
  779. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  780. if (rsa)
  781. crypto_free_pk_env(rsa);
  782. tor_free(nickname);
  783. tor_free(nn2);
  784. return result;
  785. error:
  786. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  787. tor_free(nickname);
  788. tor_free(nn2);
  789. if (pkey)
  790. EVP_PKEY_free(pkey);
  791. if (rsa)
  792. crypto_free_pk_env(rsa);
  793. if (result)
  794. tor_tls_context_decref(result);
  795. if (cert)
  796. X509_free(cert);
  797. if (idcert)
  798. X509_free(idcert);
  799. return NULL;
  800. }
  801. #ifdef V2_HANDSHAKE_SERVER
  802. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  803. * a list that indicates that the client knows how to do the v2 TLS connection
  804. * handshake. */
  805. static int
  806. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  807. {
  808. int i;
  809. SSL_SESSION *session;
  810. /* If we reached this point, we just got a client hello. See if there is
  811. * a cipher list. */
  812. if (!(session = SSL_get_session((SSL *)ssl))) {
  813. log_info(LD_NET, "No session on TLS?");
  814. return 0;
  815. }
  816. if (!session->ciphers) {
  817. log_info(LD_NET, "No ciphers on session");
  818. return 0;
  819. }
  820. /* Now we need to see if there are any ciphers whose presence means we're
  821. * dealing with an updated Tor. */
  822. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  823. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  824. const char *ciphername = SSL_CIPHER_get_name(cipher);
  825. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  826. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  827. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  828. strcmp(ciphername, "(NONE)")) {
  829. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  830. // return 1;
  831. goto dump_list;
  832. }
  833. }
  834. return 0;
  835. dump_list:
  836. {
  837. smartlist_t *elts = smartlist_create();
  838. char *s;
  839. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  840. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  841. const char *ciphername = SSL_CIPHER_get_name(cipher);
  842. smartlist_add(elts, (char*)ciphername);
  843. }
  844. s = smartlist_join_strings(elts, ":", 0, NULL);
  845. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  846. address, s);
  847. tor_free(s);
  848. smartlist_free(elts);
  849. }
  850. return 1;
  851. }
  852. static void
  853. tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
  854. {
  855. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  856. ssl, ssl_state_to_string(ssl->state), type, val);
  857. }
  858. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  859. * changes state. We use this:
  860. * <ul><li>To alter the state of the handshake partway through, so we
  861. * do not send or request extra certificates in v2 handshakes.</li>
  862. * <li>To detect renegotiation</li></ul>
  863. */
  864. static void
  865. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  866. {
  867. tor_tls_t *tls;
  868. (void) val;
  869. tor_tls_debug_state_callback(ssl, type, val);
  870. if (type != SSL_CB_ACCEPT_LOOP)
  871. return;
  872. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  873. return;
  874. tls = tor_tls_get_by_ssl(ssl);
  875. if (tls) {
  876. /* Check whether we're watching for renegotiates. If so, this is one! */
  877. if (tls->negotiated_callback)
  878. tls->got_renegotiate = 1;
  879. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  880. ++tls->server_handshake_count;
  881. } else {
  882. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  883. return;
  884. }
  885. /* Now check the cipher list. */
  886. if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
  887. /*XXXX_TLS keep this from happening more than once! */
  888. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  889. * Let's hope openssl doesn't notice! */
  890. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  891. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  892. /* Don't send a hello request. */
  893. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  894. if (tls) {
  895. tls->wasV2Handshake = 1;
  896. #ifdef USE_BUFFEREVENTS
  897. if (use_unsafe_renegotiation_flag)
  898. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  899. #endif
  900. } else {
  901. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  902. }
  903. }
  904. }
  905. #endif
  906. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  907. * a list designed to mimic a common web browser. Some of the ciphers in the
  908. * list won't actually be implemented by OpenSSL: that's okay so long as the
  909. * server doesn't select them, and the server won't select anything besides
  910. * what's in SERVER_CIPHER_LIST.
  911. *
  912. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  913. * anything; we'll just fail later when we try to look up the cipher in
  914. * ssl->cipher_list_by_id.]
  915. */
  916. static void
  917. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  918. {
  919. #ifdef V2_HANDSHAKE_CLIENT
  920. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  921. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  922. * we want.*/
  923. int i = 0, j = 0;
  924. /* First, create a dummy SSL_CIPHER for every cipher. */
  925. CLIENT_CIPHER_DUMMIES =
  926. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  927. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  928. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  929. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  930. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  931. }
  932. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  933. tor_assert(CLIENT_CIPHER_STACK);
  934. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  935. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  936. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  937. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  938. }
  939. /* Then copy as many ciphers as we can from the good list, inserting
  940. * dummies as needed. */
  941. j=0;
  942. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  943. SSL_CIPHER *cipher = NULL;
  944. if (j < sk_SSL_CIPHER_num(*ciphers))
  945. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  946. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  947. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  948. ++j;
  949. } else if (cipher &&
  950. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  951. log_debug(LD_NET, "Found cipher %s", cipher->name);
  952. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  953. ++j;
  954. ++i;
  955. } else {
  956. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  957. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  958. ++i;
  959. }
  960. }
  961. }
  962. sk_SSL_CIPHER_free(*ciphers);
  963. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  964. tor_assert(*ciphers);
  965. #else
  966. (void)ciphers;
  967. #endif
  968. }
  969. /** Create a new TLS object from a file descriptor, and a flag to
  970. * determine whether it is functioning as a server.
  971. */
  972. tor_tls_t *
  973. tor_tls_new(int sock, int isServer)
  974. {
  975. BIO *bio = NULL;
  976. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  977. tor_tls_context_t *context = isServer ? server_tls_context :
  978. client_tls_context;
  979. result->magic = TOR_TLS_MAGIC;
  980. tor_assert(context); /* make sure somebody made it first */
  981. if (!(result->ssl = SSL_new(context->ctx))) {
  982. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  983. tor_free(result);
  984. return NULL;
  985. }
  986. #ifdef SSL_set_tlsext_host_name
  987. /* Browsers use the TLS hostname extension, so we should too. */
  988. if (!isServer) {
  989. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  990. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  991. tor_free(fake_hostname);
  992. }
  993. #endif
  994. if (!SSL_set_cipher_list(result->ssl,
  995. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  996. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  997. #ifdef SSL_set_tlsext_host_name
  998. SSL_set_tlsext_host_name(result->ssl, NULL);
  999. #endif
  1000. SSL_free(result->ssl);
  1001. tor_free(result);
  1002. return NULL;
  1003. }
  1004. if (!isServer)
  1005. rectify_client_ciphers(&result->ssl->cipher_list);
  1006. result->socket = sock;
  1007. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1008. if (! bio) {
  1009. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1010. #ifdef SSL_set_tlsext_host_name
  1011. SSL_set_tlsext_host_name(result->ssl, NULL);
  1012. #endif
  1013. SSL_free(result->ssl);
  1014. tor_free(result);
  1015. return NULL;
  1016. }
  1017. {
  1018. int set_worked =
  1019. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1020. if (!set_worked) {
  1021. log_warn(LD_BUG,
  1022. "Couldn't set the tls for an SSL*; connection will fail");
  1023. }
  1024. }
  1025. SSL_set_bio(result->ssl, bio, bio);
  1026. tor_tls_context_incref(context);
  1027. result->context = context;
  1028. result->state = TOR_TLS_ST_HANDSHAKE;
  1029. result->isServer = isServer;
  1030. result->wantwrite_n = 0;
  1031. result->last_write_count = BIO_number_written(bio);
  1032. result->last_read_count = BIO_number_read(bio);
  1033. if (result->last_write_count || result->last_read_count) {
  1034. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1035. result->last_read_count, result->last_write_count);
  1036. }
  1037. #ifdef V2_HANDSHAKE_SERVER
  1038. if (isServer) {
  1039. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  1040. } else
  1041. #endif
  1042. {
  1043. SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
  1044. }
  1045. /* Not expected to get called. */
  1046. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1047. return result;
  1048. }
  1049. /** Make future log messages about <b>tls</b> display the address
  1050. * <b>address</b>.
  1051. */
  1052. void
  1053. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1054. {
  1055. tor_assert(tls);
  1056. tor_free(tls->address);
  1057. tls->address = tor_strdup(address);
  1058. }
  1059. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  1060. * next gets a client-side renegotiate in the middle of a read. Do not
  1061. * invoke this function until <em>after</em> initial handshaking is done!
  1062. */
  1063. void
  1064. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  1065. void (*cb)(tor_tls_t *, void *arg),
  1066. void *arg)
  1067. {
  1068. tls->negotiated_callback = cb;
  1069. tls->callback_arg = arg;
  1070. tls->got_renegotiate = 0;
  1071. #ifdef V2_HANDSHAKE_SERVER
  1072. if (cb) {
  1073. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  1074. } else {
  1075. SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
  1076. }
  1077. #endif
  1078. }
  1079. /** If this version of openssl requires it, turn on renegotiation on
  1080. * <b>tls</b>.
  1081. */
  1082. void
  1083. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1084. {
  1085. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1086. * as authenticating any earlier-received data. */
  1087. if (use_unsafe_renegotiation_flag) {
  1088. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1089. }
  1090. if (use_unsafe_renegotiation_op) {
  1091. SSL_set_options(tls->ssl,
  1092. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1093. }
  1094. }
  1095. /** If this version of openssl supports it, turn off renegotiation on
  1096. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  1097. * to use belt-and-suspenders here.)
  1098. */
  1099. void
  1100. tor_tls_block_renegotiation(tor_tls_t *tls)
  1101. {
  1102. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1103. }
  1104. void
  1105. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1106. {
  1107. if (use_unsafe_renegotiation_flag) {
  1108. tor_assert(0 != (tls->ssl->s3->flags &
  1109. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1110. }
  1111. if (use_unsafe_renegotiation_op) {
  1112. long options = SSL_get_options(tls->ssl);
  1113. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1114. }
  1115. }
  1116. /** Return whether this tls initiated the connect (client) or
  1117. * received it (server). */
  1118. int
  1119. tor_tls_is_server(tor_tls_t *tls)
  1120. {
  1121. tor_assert(tls);
  1122. return tls->isServer;
  1123. }
  1124. /** Release resources associated with a TLS object. Does not close the
  1125. * underlying file descriptor.
  1126. */
  1127. void
  1128. tor_tls_free(tor_tls_t *tls)
  1129. {
  1130. if (!tls)
  1131. return;
  1132. tor_assert(tls->ssl);
  1133. #ifdef SSL_set_tlsext_host_name
  1134. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1135. #endif
  1136. SSL_free(tls->ssl);
  1137. tls->ssl = NULL;
  1138. tls->negotiated_callback = NULL;
  1139. if (tls->context)
  1140. tor_tls_context_decref(tls->context);
  1141. tor_free(tls->address);
  1142. tls->magic = 0x99999999;
  1143. tor_free(tls);
  1144. }
  1145. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1146. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1147. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1148. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1149. */
  1150. int
  1151. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1152. {
  1153. int r, err;
  1154. tor_assert(tls);
  1155. tor_assert(tls->ssl);
  1156. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1157. tor_assert(len<INT_MAX);
  1158. r = SSL_read(tls->ssl, cp, (int)len);
  1159. if (r > 0) {
  1160. #ifdef V2_HANDSHAKE_SERVER
  1161. if (tls->got_renegotiate) {
  1162. /* Renegotiation happened! */
  1163. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1164. if (tls->negotiated_callback)
  1165. tls->negotiated_callback(tls, tls->callback_arg);
  1166. tls->got_renegotiate = 0;
  1167. }
  1168. #endif
  1169. return r;
  1170. }
  1171. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1172. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1173. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1174. tls->state = TOR_TLS_ST_CLOSED;
  1175. return TOR_TLS_CLOSE;
  1176. } else {
  1177. tor_assert(err != TOR_TLS_DONE);
  1178. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1179. return err;
  1180. }
  1181. }
  1182. /** Underlying function for TLS writing. Write up to <b>n</b>
  1183. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1184. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1185. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1186. */
  1187. int
  1188. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1189. {
  1190. int r, err;
  1191. tor_assert(tls);
  1192. tor_assert(tls->ssl);
  1193. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1194. tor_assert(n < INT_MAX);
  1195. if (n == 0)
  1196. return 0;
  1197. if (tls->wantwrite_n) {
  1198. /* if WANTWRITE last time, we must use the _same_ n as before */
  1199. tor_assert(n >= tls->wantwrite_n);
  1200. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1201. (int)n, (int)tls->wantwrite_n);
  1202. n = tls->wantwrite_n;
  1203. tls->wantwrite_n = 0;
  1204. }
  1205. r = SSL_write(tls->ssl, cp, (int)n);
  1206. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1207. if (err == TOR_TLS_DONE) {
  1208. return r;
  1209. }
  1210. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1211. tls->wantwrite_n = n;
  1212. }
  1213. return err;
  1214. }
  1215. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1216. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1217. * or TOR_TLS_WANTWRITE.
  1218. */
  1219. int
  1220. tor_tls_handshake(tor_tls_t *tls)
  1221. {
  1222. int r;
  1223. int oldstate;
  1224. tor_assert(tls);
  1225. tor_assert(tls->ssl);
  1226. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1227. check_no_tls_errors();
  1228. oldstate = tls->ssl->state;
  1229. if (tls->isServer) {
  1230. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1231. ssl_state_to_string(tls->ssl->state));
  1232. r = SSL_accept(tls->ssl);
  1233. } else {
  1234. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1235. ssl_state_to_string(tls->ssl->state));
  1236. r = SSL_connect(tls->ssl);
  1237. }
  1238. if (oldstate != tls->ssl->state)
  1239. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1240. tls, ssl_state_to_string(tls->ssl->state));
  1241. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1242. * for clearing its flags when you say accept or connect. */
  1243. tor_tls_unblock_renegotiation(tls);
  1244. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1245. if (ERR_peek_error() != 0) {
  1246. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1247. "handshaking");
  1248. return TOR_TLS_ERROR_MISC;
  1249. }
  1250. if (r == TOR_TLS_DONE) {
  1251. tls->state = TOR_TLS_ST_OPEN;
  1252. return tor_tls_finish_handshake(tls);
  1253. }
  1254. return r;
  1255. }
  1256. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1257. * should be called for the first handshake only: it determines whether the v1
  1258. * or the v2 handshake was used, and adjusts things for the renegotiation
  1259. * handshake as appropriate.
  1260. *
  1261. * tor_tls_handshake() calls this on its own; you only need to call this if
  1262. * bufferevent is doing the handshake for you.
  1263. */
  1264. int
  1265. tor_tls_finish_handshake(tor_tls_t *tls)
  1266. {
  1267. int r = TOR_TLS_DONE;
  1268. if (tls->isServer) {
  1269. SSL_set_info_callback(tls->ssl, NULL);
  1270. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1271. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1272. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1273. #ifdef V2_HANDSHAKE_SERVER
  1274. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1275. /* This check is redundant, but back when we did it in the callback,
  1276. * we might have not been able to look up the tor_tls_t if the code
  1277. * was buggy. Fixing that. */
  1278. if (!tls->wasV2Handshake) {
  1279. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1280. " get set. Fixing that.");
  1281. }
  1282. tls->wasV2Handshake = 1;
  1283. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1284. " for renegotiation.");
  1285. } else {
  1286. tls->wasV2Handshake = 0;
  1287. }
  1288. #endif
  1289. } else {
  1290. #ifdef V2_HANDSHAKE_CLIENT
  1291. /* If we got no ID cert, we're a v2 handshake. */
  1292. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1293. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1294. int n_certs = sk_X509_num(chain);
  1295. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1296. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1297. "looks like a v1 handshake on %p", tls);
  1298. tls->wasV2Handshake = 0;
  1299. } else {
  1300. log_debug(LD_HANDSHAKE,
  1301. "Server sent back a single certificate; looks like "
  1302. "a v2 handshake on %p.", tls);
  1303. tls->wasV2Handshake = 1;
  1304. }
  1305. if (cert)
  1306. X509_free(cert);
  1307. #endif
  1308. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1309. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1310. r = TOR_TLS_ERROR_MISC;
  1311. }
  1312. }
  1313. return r;
  1314. }
  1315. #ifdef USE_BUFFEREVENTS
  1316. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1317. * mode. */
  1318. int
  1319. tor_tls_start_renegotiating(tor_tls_t *tls)
  1320. {
  1321. int r = SSL_renegotiate(tls->ssl);
  1322. if (r <= 0) {
  1323. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1324. LD_HANDSHAKE);
  1325. }
  1326. return 0;
  1327. }
  1328. #endif
  1329. /** Client only: Renegotiate a TLS session. When finished, returns
  1330. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1331. * TOR_TLS_WANTWRITE.
  1332. */
  1333. int
  1334. tor_tls_renegotiate(tor_tls_t *tls)
  1335. {
  1336. int r;
  1337. tor_assert(tls);
  1338. /* We could do server-initiated renegotiation too, but that would be tricky.
  1339. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1340. tor_assert(!tls->isServer);
  1341. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1342. int r = SSL_renegotiate(tls->ssl);
  1343. if (r <= 0) {
  1344. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1345. LD_HANDSHAKE);
  1346. }
  1347. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1348. }
  1349. r = SSL_do_handshake(tls->ssl);
  1350. if (r == 1) {
  1351. tls->state = TOR_TLS_ST_OPEN;
  1352. return TOR_TLS_DONE;
  1353. } else
  1354. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1355. LD_HANDSHAKE);
  1356. }
  1357. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1358. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1359. * or TOR_TLS_WANTWRITE.
  1360. */
  1361. int
  1362. tor_tls_shutdown(tor_tls_t *tls)
  1363. {
  1364. int r, err;
  1365. char buf[128];
  1366. tor_assert(tls);
  1367. tor_assert(tls->ssl);
  1368. while (1) {
  1369. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1370. /* If we've already called shutdown once to send a close message,
  1371. * we read until the other side has closed too.
  1372. */
  1373. do {
  1374. r = SSL_read(tls->ssl, buf, 128);
  1375. } while (r>0);
  1376. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1377. LOG_INFO, LD_NET);
  1378. if (err == _TOR_TLS_ZERORETURN) {
  1379. tls->state = TOR_TLS_ST_GOTCLOSE;
  1380. /* fall through... */
  1381. } else {
  1382. return err;
  1383. }
  1384. }
  1385. r = SSL_shutdown(tls->ssl);
  1386. if (r == 1) {
  1387. /* If shutdown returns 1, the connection is entirely closed. */
  1388. tls->state = TOR_TLS_ST_CLOSED;
  1389. return TOR_TLS_DONE;
  1390. }
  1391. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1392. LOG_INFO, LD_NET);
  1393. if (err == _TOR_TLS_SYSCALL) {
  1394. /* The underlying TCP connection closed while we were shutting down. */
  1395. tls->state = TOR_TLS_ST_CLOSED;
  1396. return TOR_TLS_DONE;
  1397. } else if (err == _TOR_TLS_ZERORETURN) {
  1398. /* The TLS connection says that it sent a shutdown record, but
  1399. * isn't done shutting down yet. Make sure that this hasn't
  1400. * happened before, then go back to the start of the function
  1401. * and try to read.
  1402. */
  1403. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1404. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1405. log(LOG_WARN, LD_NET,
  1406. "TLS returned \"half-closed\" value while already half-closed");
  1407. return TOR_TLS_ERROR_MISC;
  1408. }
  1409. tls->state = TOR_TLS_ST_SENTCLOSE;
  1410. /* fall through ... */
  1411. } else {
  1412. return err;
  1413. }
  1414. } /* end loop */
  1415. }
  1416. /** Return true iff this TLS connection is authenticated.
  1417. */
  1418. int
  1419. tor_tls_peer_has_cert(tor_tls_t *tls)
  1420. {
  1421. X509 *cert;
  1422. cert = SSL_get_peer_certificate(tls->ssl);
  1423. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1424. if (!cert)
  1425. return 0;
  1426. X509_free(cert);
  1427. return 1;
  1428. }
  1429. /** Warn that a certificate lifetime extends through a certain range. */
  1430. static void
  1431. log_cert_lifetime(X509 *cert, const char *problem)
  1432. {
  1433. BIO *bio = NULL;
  1434. BUF_MEM *buf;
  1435. char *s1=NULL, *s2=NULL;
  1436. char mytime[33];
  1437. time_t now = time(NULL);
  1438. struct tm tm;
  1439. if (problem)
  1440. log_warn(LD_GENERAL,
  1441. "Certificate %s: is your system clock set incorrectly?",
  1442. problem);
  1443. if (!(bio = BIO_new(BIO_s_mem()))) {
  1444. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1445. }
  1446. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1447. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1448. goto end;
  1449. }
  1450. BIO_get_mem_ptr(bio, &buf);
  1451. s1 = tor_strndup(buf->data, buf->length);
  1452. (void)BIO_reset(bio);
  1453. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1454. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1455. goto end;
  1456. }
  1457. BIO_get_mem_ptr(bio, &buf);
  1458. s2 = tor_strndup(buf->data, buf->length);
  1459. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1460. log_warn(LD_GENERAL,
  1461. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1462. s1,s2,mytime);
  1463. end:
  1464. /* Not expected to get invoked */
  1465. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1466. if (bio)
  1467. BIO_free(bio);
  1468. tor_free(s1);
  1469. tor_free(s2);
  1470. }
  1471. /** Helper function: try to extract a link certificate and an identity
  1472. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1473. * *<b>id_cert_out</b> respectively. Log all messages at level
  1474. * <b>severity</b>.
  1475. *
  1476. * Note that a reference is added to cert_out, so it needs to be
  1477. * freed. id_cert_out doesn't. */
  1478. static void
  1479. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1480. X509 **cert_out, X509 **id_cert_out)
  1481. {
  1482. X509 *cert = NULL, *id_cert = NULL;
  1483. STACK_OF(X509) *chain = NULL;
  1484. int num_in_chain, i;
  1485. *cert_out = *id_cert_out = NULL;
  1486. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1487. return;
  1488. *cert_out = cert;
  1489. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1490. return;
  1491. num_in_chain = sk_X509_num(chain);
  1492. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1493. * 2 means we're connecting (client-side), and it's both the link
  1494. * cert and the id_cert.
  1495. */
  1496. if (num_in_chain < 1) {
  1497. log_fn(severity,LD_PROTOCOL,
  1498. "Unexpected number of certificates in chain (%d)",
  1499. num_in_chain);
  1500. return;
  1501. }
  1502. for (i=0; i<num_in_chain; ++i) {
  1503. id_cert = sk_X509_value(chain, i);
  1504. if (X509_cmp(id_cert, cert) != 0)
  1505. break;
  1506. }
  1507. *id_cert_out = id_cert;
  1508. }
  1509. /** If the provided tls connection is authenticated and has a
  1510. * certificate chain that is currently valid and signed, then set
  1511. * *<b>identity_key</b> to the identity certificate's key and return
  1512. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1513. */
  1514. int
  1515. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1516. {
  1517. X509 *cert = NULL, *id_cert = NULL;
  1518. EVP_PKEY *id_pkey = NULL;
  1519. RSA *rsa;
  1520. int r = -1;
  1521. *identity_key = NULL;
  1522. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1523. if (!cert)
  1524. goto done;
  1525. if (!id_cert) {
  1526. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1527. goto done;
  1528. }
  1529. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1530. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1531. X509_verify(cert, id_pkey) <= 0) {
  1532. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1533. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1534. goto done;
  1535. }
  1536. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1537. if (!rsa)
  1538. goto done;
  1539. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1540. r = 0;
  1541. done:
  1542. if (cert)
  1543. X509_free(cert);
  1544. if (id_pkey)
  1545. EVP_PKEY_free(id_pkey);
  1546. /* This should never get invoked, but let's make sure in case OpenSSL
  1547. * acts unexpectedly. */
  1548. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1549. return r;
  1550. }
  1551. /** Check whether the certificate set on the connection <b>tls</b> is
  1552. * expired or not-yet-valid, give or take <b>tolerance</b>
  1553. * seconds. Return 0 for valid, -1 for failure.
  1554. *
  1555. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1556. */
  1557. int
  1558. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1559. {
  1560. time_t now, t;
  1561. X509 *cert;
  1562. int r = -1;
  1563. now = time(NULL);
  1564. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1565. goto done;
  1566. t = now + tolerance;
  1567. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1568. log_cert_lifetime(cert, "not yet valid");
  1569. goto done;
  1570. }
  1571. t = now - tolerance;
  1572. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1573. log_cert_lifetime(cert, "already expired");
  1574. goto done;
  1575. }
  1576. r = 0;
  1577. done:
  1578. if (cert)
  1579. X509_free(cert);
  1580. /* Not expected to get invoked */
  1581. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1582. return r;
  1583. }
  1584. /** Return the number of bytes available for reading from <b>tls</b>.
  1585. */
  1586. int
  1587. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1588. {
  1589. tor_assert(tls);
  1590. return SSL_pending(tls->ssl);
  1591. }
  1592. /** If <b>tls</b> requires that the next write be of a particular size,
  1593. * return that size. Otherwise, return 0. */
  1594. size_t
  1595. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1596. {
  1597. return tls->wantwrite_n;
  1598. }
  1599. /** Sets n_read and n_written to the number of bytes read and written,
  1600. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1601. * function was called on <b>tls</b>. */
  1602. void
  1603. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1604. {
  1605. BIO *wbio, *tmpbio;
  1606. unsigned long r, w;
  1607. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1608. /* We want the number of bytes actually for real written. Unfortunately,
  1609. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1610. * which makes the answer turn out wrong. Let's cope with that. Note
  1611. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1612. * buffering bios for reasons of our own. As an alternative, we could
  1613. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1614. * that would be tempting fate. */
  1615. wbio = SSL_get_wbio(tls->ssl);
  1616. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1617. wbio = tmpbio;
  1618. w = BIO_number_written(wbio);
  1619. /* We are ok with letting these unsigned ints go "negative" here:
  1620. * If we wrapped around, this should still give us the right answer, unless
  1621. * we wrapped around by more than ULONG_MAX since the last time we called
  1622. * this function.
  1623. */
  1624. *n_read = (size_t)(r - tls->last_read_count);
  1625. *n_written = (size_t)(w - tls->last_write_count);
  1626. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  1627. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  1628. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  1629. r, tls->last_read_count, w, tls->last_write_count);
  1630. }
  1631. tls->last_read_count = r;
  1632. tls->last_write_count = w;
  1633. }
  1634. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1635. * errors, log an error message. */
  1636. void
  1637. _check_no_tls_errors(const char *fname, int line)
  1638. {
  1639. if (ERR_peek_error() == 0)
  1640. return;
  1641. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1642. tor_fix_source_file(fname), line);
  1643. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  1644. }
  1645. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  1646. * TLS handshake. Output is undefined if the handshake isn't finished. */
  1647. int
  1648. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1649. {
  1650. if (tls->isServer) {
  1651. #ifdef V2_HANDSHAKE_SERVER
  1652. return ! tls->wasV2Handshake;
  1653. #endif
  1654. } else {
  1655. #ifdef V2_HANDSHAKE_CLIENT
  1656. return ! tls->wasV2Handshake;
  1657. #endif
  1658. }
  1659. return 1;
  1660. }
  1661. /** Return the number of server handshakes that we've noticed doing on
  1662. * <b>tls</b>. */
  1663. int
  1664. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  1665. {
  1666. return tls->server_handshake_count;
  1667. }
  1668. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  1669. * request it was waiting for. */
  1670. int
  1671. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  1672. {
  1673. return tls->got_renegotiate;
  1674. }
  1675. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  1676. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  1677. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  1678. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  1679. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  1680. void
  1681. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  1682. size_t *rbuf_capacity, size_t *rbuf_bytes,
  1683. size_t *wbuf_capacity, size_t *wbuf_bytes)
  1684. {
  1685. if (tls->ssl->s3->rbuf.buf)
  1686. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  1687. else
  1688. *rbuf_capacity = 0;
  1689. if (tls->ssl->s3->wbuf.buf)
  1690. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  1691. else
  1692. *wbuf_capacity = 0;
  1693. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  1694. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  1695. }
  1696. #ifdef USE_BUFFEREVENTS
  1697. /** Construct and return an TLS-encrypting bufferevent to send data over
  1698. * <b>socket</b>, which must match the socket of the underlying bufferevent
  1699. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  1700. *
  1701. * This function will either create a filtering bufferevent that wraps around
  1702. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  1703. * uses the <b>tls</b> to talk to the network directly. Do not use
  1704. * <b>bufev_in</b> after calling this function.
  1705. *
  1706. * The connection will start out doing a server handshake if <b>receiving</b>
  1707. * is strue, and a client handshake otherwise.
  1708. *
  1709. * Returns NULL on failure.
  1710. */
  1711. struct bufferevent *
  1712. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  1713. evutil_socket_t socket, int receiving,
  1714. int filter)
  1715. {
  1716. struct bufferevent *out;
  1717. const enum bufferevent_ssl_state state = receiving ?
  1718. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  1719. if (filter) {
  1720. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  1721. means that the SSL will get freed too.
  1722. This increment makes our SSL usage not-threadsafe, BTW. We should
  1723. see if we're allowed to use CRYPTO_add from outside openssl. */
  1724. tls->ssl->references += 1;
  1725. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  1726. bufev_in,
  1727. tls->ssl,
  1728. state,
  1729. BEV_OPT_DEFER_CALLBACKS|
  1730. BEV_OPT_CLOSE_ON_FREE);
  1731. } else {
  1732. if (bufev_in) {
  1733. evutil_socket_t s = bufferevent_getfd(bufev_in);
  1734. tor_assert(s == -1 || s == socket);
  1735. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  1736. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  1737. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  1738. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  1739. bufferevent_free(bufev_in);
  1740. }
  1741. /* Current versions (as of 2.0.x) of Libevent need to defer
  1742. * bufferevent_openssl callbacks, or else our callback functions will
  1743. * get called reentrantly, which is bad for us.
  1744. */
  1745. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  1746. socket,
  1747. tls->ssl,
  1748. state,
  1749. BEV_OPT_DEFER_CALLBACKS);
  1750. }
  1751. tls->state = TOR_TLS_ST_BUFFEREVENT;
  1752. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  1753. * clear flags. */
  1754. tor_tls_unblock_renegotiation(tls);
  1755. return out;
  1756. }
  1757. #endif