tortls.c 50 KB

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