tortls.c 60 KB

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