tortls.c 61 KB

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