tortls.c 42 KB

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