tortls.c 58 KB

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