tortls.c 59 KB

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