tortls.c 45 KB

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