tortls.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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);
  511. X509_free(idcert); /* The context now owns the reference to idcert */
  512. idcert = NULL;
  513. }
  514. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  515. tor_assert(rsa);
  516. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  517. goto error;
  518. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  519. goto error;
  520. EVP_PKEY_free(pkey);
  521. pkey = NULL;
  522. if (!SSL_CTX_check_private_key(result->ctx))
  523. goto error;
  524. dh = crypto_dh_new();
  525. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  526. crypto_dh_free(dh);
  527. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  528. always_accept_verify_cb);
  529. /* let us realloc bufs that we're writing from */
  530. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  531. /* Free the old context if one exists. */
  532. if (global_tls_context) {
  533. /* This is safe even if there are open connections: OpenSSL does
  534. * reference counting with SSL and SSL_CTX objects. */
  535. tor_tls_context_decref(global_tls_context);
  536. }
  537. global_tls_context = result;
  538. if (rsa)
  539. crypto_free_pk_env(rsa);
  540. return 0;
  541. error:
  542. tls_log_errors(LOG_WARN, "creating TLS context");
  543. if (pkey)
  544. EVP_PKEY_free(pkey);
  545. if (rsa)
  546. crypto_free_pk_env(rsa);
  547. if (dh)
  548. crypto_dh_free(dh);
  549. if (result)
  550. tor_tls_context_decref(result);
  551. if (cert)
  552. X509_free(cert);
  553. if (idcert)
  554. X509_free(idcert);
  555. return -1;
  556. }
  557. #ifdef V2_HANDSHAKE_SERVER
  558. /** DOCDOC */
  559. static int
  560. tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
  561. {
  562. int i;
  563. SSL_SESSION *session;
  564. /* If we reached this point, we just got a client hello. See if there is
  565. * a cipher list. */
  566. if (!(session = SSL_get_session(ssl))) {
  567. log_warn(LD_NET, "No session on TLS?");
  568. return 0;
  569. }
  570. if (!session->ciphers) {
  571. log_warn(LD_NET, "No ciphers on session");
  572. return 0;
  573. }
  574. /* Now we need to see if there are any ciphers whose presence means we're
  575. * dealing with an updated Tor. */
  576. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  577. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  578. const char *ciphername = SSL_CIPHER_get_name(cipher);
  579. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  580. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  581. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  582. strcmp(ciphername, "(NONE)")) {
  583. /* XXXX should be ld_debug */
  584. log_info(LD_NET, "Got a non-version-1 cipher called '%s'",ciphername);
  585. // return 1;
  586. goto dump_list;
  587. }
  588. }
  589. return 0;
  590. dump_list:
  591. {
  592. smartlist_t *elts = smartlist_create();
  593. char *s;
  594. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  595. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  596. const char *ciphername = SSL_CIPHER_get_name(cipher);
  597. smartlist_add(elts, (char*)ciphername);
  598. }
  599. s = smartlist_join_strings(elts, ":", 0, NULL);
  600. log_info(LD_NET, "Got a non-version-1 cipher list. It is: '%s'", s);
  601. tor_free(s);
  602. smartlist_free(elts);
  603. }
  604. return 1;
  605. }
  606. /** DOCDOC */
  607. static void
  608. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  609. {
  610. (void) val;
  611. if (type != SSL_CB_ACCEPT_LOOP)
  612. return;
  613. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  614. return;
  615. if (tor_tls_client_is_using_v2_ciphers(ssl)) {
  616. tor_tls_t *tls;
  617. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  618. * Let's hope openssl doesn't notice! */
  619. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  620. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  621. /* Don't send a hello request. */
  622. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  623. tls = tor_tls_get_by_ssl((SSL*)ssl);
  624. if (tls) {
  625. tls->wasV2Handshake = 1;
  626. } else {
  627. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  628. }
  629. }
  630. }
  631. #endif
  632. /** Create a new TLS object from a file descriptor, and a flag to
  633. * determine whether it is functioning as a server.
  634. */
  635. tor_tls_t *
  636. tor_tls_new(int sock, int isServer)
  637. {
  638. BIO *bio = NULL;
  639. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  640. tor_assert(global_tls_context); /* make sure somebody made it first */
  641. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  642. tls_log_errors(LOG_WARN, "generating TLS context");
  643. tor_free(result);
  644. return NULL;
  645. }
  646. if (!SSL_set_cipher_list(result->ssl,
  647. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  648. SSL_free(result->ssl);
  649. tor_free(result);
  650. return NULL;
  651. }
  652. result->socket = sock;
  653. #ifdef USE_BSOCKETS
  654. bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
  655. #else
  656. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  657. #endif
  658. if (! bio) {
  659. tls_log_errors(LOG_WARN, "opening BIO");
  660. SSL_free(result->ssl);
  661. tor_free(result);
  662. return NULL;
  663. }
  664. HT_INSERT(tlsmap, &tlsmap_root, result);
  665. SSL_set_bio(result->ssl, bio, bio);
  666. tor_tls_context_incref(global_tls_context);
  667. result->context = global_tls_context;
  668. result->state = TOR_TLS_ST_HANDSHAKE;
  669. result->isServer = isServer;
  670. result->wantwrite_n = 0;
  671. #ifdef V2_HANDSHAKE_SERVER
  672. if (isServer) {
  673. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  674. }
  675. #endif
  676. /* Not expected to get called. */
  677. tls_log_errors(LOG_WARN, "generating TLS context");
  678. return result;
  679. }
  680. /**DOCDOC*/
  681. void
  682. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  683. void (*cb)(tor_tls_t *, void *arg),
  684. void *arg)
  685. {
  686. tls->negotiated_callback = cb;
  687. tls->callback_arg = arg;
  688. }
  689. /** Return whether this tls initiated the connect (client) or
  690. * received it (server). */
  691. int
  692. tor_tls_is_server(tor_tls_t *tls)
  693. {
  694. tor_assert(tls);
  695. return tls->isServer;
  696. }
  697. /** Release resources associated with a TLS object. Does not close the
  698. * underlying file descriptor.
  699. */
  700. void
  701. tor_tls_free(tor_tls_t *tls)
  702. {
  703. tor_tls_t *removed;
  704. tor_assert(tls && tls->ssl);
  705. removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
  706. if (!removed) {
  707. log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
  708. }
  709. SSL_free(tls->ssl);
  710. tls->ssl = NULL;
  711. tls->negotiated_callback = NULL;
  712. if (tls->context)
  713. tor_tls_context_decref(tls->context);
  714. tor_free(tls);
  715. }
  716. /** Underlying function for TLS reading. Reads up to <b>len</b>
  717. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  718. * number of characters read. On failure, returns TOR_TLS_ERROR,
  719. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  720. */
  721. int
  722. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  723. {
  724. int r, err;
  725. tor_assert(tls);
  726. tor_assert(tls->ssl);
  727. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  728. r = SSL_read(tls->ssl, cp, len);
  729. if (r > 0) {
  730. #ifdef V2_HANDSHAKE_SERVER
  731. if (!tls->hadCert && tls->ssl->session && tls->ssl->session->peer) {
  732. tls->hadCert = 1;
  733. /* New certificate! */
  734. log_info(LD_NET, "Got a TLS renegotiation.");
  735. if (tls->negotiated_callback)
  736. tls->negotiated_callback(tls, tls->callback_arg);
  737. }
  738. #endif
  739. return r;
  740. }
  741. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
  742. if (err == _TOR_TLS_ZERORETURN) {
  743. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  744. tls->state = TOR_TLS_ST_CLOSED;
  745. return TOR_TLS_CLOSE;
  746. } else {
  747. tor_assert(err != TOR_TLS_DONE);
  748. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  749. return err;
  750. }
  751. }
  752. /** Underlying function for TLS writing. Write up to <b>n</b>
  753. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  754. * number of characters written. On failure, returns TOR_TLS_ERROR,
  755. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  756. */
  757. int
  758. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  759. {
  760. int r, err;
  761. tor_assert(tls);
  762. tor_assert(tls->ssl);
  763. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  764. if (n == 0)
  765. return 0;
  766. if (tls->wantwrite_n) {
  767. /* if WANTWRITE last time, we must use the _same_ n as before */
  768. tor_assert(n >= tls->wantwrite_n);
  769. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  770. (int)n, (int)tls->wantwrite_n);
  771. n = tls->wantwrite_n;
  772. tls->wantwrite_n = 0;
  773. }
  774. r = SSL_write(tls->ssl, cp, n);
  775. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  776. if (err == TOR_TLS_DONE) {
  777. return r;
  778. }
  779. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  780. tls->wantwrite_n = n;
  781. }
  782. return err;
  783. }
  784. /** Perform initial handshake on <b>tls</b>. When finished, returns
  785. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  786. * or TOR_TLS_WANTWRITE.
  787. */
  788. int
  789. tor_tls_handshake(tor_tls_t *tls)
  790. {
  791. int r;
  792. tor_assert(tls);
  793. tor_assert(tls->ssl);
  794. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  795. check_no_tls_errors();
  796. if (tls->isServer) {
  797. r = SSL_accept(tls->ssl);
  798. } else {
  799. r = SSL_connect(tls->ssl);
  800. }
  801. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  802. if (ERR_peek_error() != 0) {
  803. tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
  804. "handshaking");
  805. return TOR_TLS_ERROR_MISC;
  806. }
  807. if (r == TOR_TLS_DONE) {
  808. tls->state = TOR_TLS_ST_OPEN;
  809. tls->hadCert = tor_tls_peer_has_cert(tls) ? 1 : 0;
  810. if (tls->isServer) {
  811. SSL_set_info_callback(tls->ssl, NULL);
  812. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, always_accept_verify_cb);
  813. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  814. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  815. #ifdef V2_HANDSHAKE_SERVER
  816. if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
  817. /* This check is redundant, but back when we did it in the callback,
  818. * we might have not been able to look up the tor_tls_t if the code
  819. * was buggy. Fixing that. */
  820. if (!tls->wasV2Handshake) {
  821. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  822. " get set. Fixing that.");
  823. }
  824. tls->wasV2Handshake = 1;
  825. } else {
  826. tls->wasV2Handshake = 0;
  827. }
  828. #endif
  829. } else {
  830. #ifdef V2_HANDSHAKE_CLIENT
  831. /* If we got no ID cert, we're a v2 handshake. */
  832. X509 *cert = SSL_get_peer_certificate(tls->ssl);/*XXXX020 refcnt?*/
  833. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  834. int n_certs = sk_X509_num(chain);
  835. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
  836. tls->wasV2Handshake = 0;
  837. else {
  838. log_notice(LD_NET, "I think I got a v2 handshake!");
  839. tls->wasV2Handshake = 1;
  840. }
  841. if (cert)
  842. X509_free(cert);
  843. #endif
  844. SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
  845. }
  846. }
  847. return r;
  848. }
  849. /** Client only: Renegotiate a TLS session. When finished, returns
  850. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  851. * TOR_TLS_WANTWRITE.
  852. */
  853. int
  854. tor_tls_renegotiate(tor_tls_t *tls)
  855. {
  856. int r;
  857. tor_assert(tls);
  858. /* We could do server-initiated renegotiation too, but that would be tricky.
  859. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  860. tor_assert(!tls->isServer);
  861. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  862. int r = SSL_renegotiate(tls->ssl);
  863. if (r <= 0) {
  864. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  865. "renegotiating", LOG_WARN);
  866. }
  867. tls->state = TOR_TLS_ST_RENEGOTIATE;
  868. }
  869. r = SSL_do_handshake(tls->ssl);
  870. if (r == 1) {
  871. tls->state = TOR_TLS_ST_OPEN;
  872. return TOR_TLS_DONE;
  873. } else
  874. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  875. "renegotiating handshake", LOG_WARN);
  876. }
  877. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  878. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  879. * or TOR_TLS_WANTWRITE.
  880. */
  881. int
  882. tor_tls_shutdown(tor_tls_t *tls)
  883. {
  884. int r, err;
  885. char buf[128];
  886. tor_assert(tls);
  887. tor_assert(tls->ssl);
  888. while (1) {
  889. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  890. /* If we've already called shutdown once to send a close message,
  891. * we read until the other side has closed too.
  892. */
  893. do {
  894. r = SSL_read(tls->ssl, buf, 128);
  895. } while (r>0);
  896. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  897. LOG_INFO);
  898. if (err == _TOR_TLS_ZERORETURN) {
  899. tls->state = TOR_TLS_ST_GOTCLOSE;
  900. /* fall through... */
  901. } else {
  902. return err;
  903. }
  904. }
  905. r = SSL_shutdown(tls->ssl);
  906. if (r == 1) {
  907. /* If shutdown returns 1, the connection is entirely closed. */
  908. tls->state = TOR_TLS_ST_CLOSED;
  909. return TOR_TLS_DONE;
  910. }
  911. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  912. LOG_INFO);
  913. if (err == _TOR_TLS_SYSCALL) {
  914. /* The underlying TCP connection closed while we were shutting down. */
  915. tls->state = TOR_TLS_ST_CLOSED;
  916. return TOR_TLS_DONE;
  917. } else if (err == _TOR_TLS_ZERORETURN) {
  918. /* The TLS connection says that it sent a shutdown record, but
  919. * isn't done shutting down yet. Make sure that this hasn't
  920. * happened before, then go back to the start of the function
  921. * and try to read.
  922. */
  923. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  924. tls->state == TOR_TLS_ST_SENTCLOSE) {
  925. log(LOG_WARN, LD_NET,
  926. "TLS returned \"half-closed\" value while already half-closed");
  927. return TOR_TLS_ERROR_MISC;
  928. }
  929. tls->state = TOR_TLS_ST_SENTCLOSE;
  930. /* fall through ... */
  931. } else {
  932. return err;
  933. }
  934. } /* end loop */
  935. }
  936. /** Return true iff this TLS connection is authenticated.
  937. */
  938. int
  939. tor_tls_peer_has_cert(tor_tls_t *tls)
  940. {
  941. X509 *cert;
  942. cert = SSL_get_peer_certificate(tls->ssl);
  943. tls_log_errors(LOG_WARN, "getting peer certificate");
  944. if (!cert)
  945. return 0;
  946. X509_free(cert);
  947. return 1;
  948. }
  949. /** DOCDOC */
  950. int
  951. tor_tls_get_cert_digests(tor_tls_t *tls,
  952. char *my_digest_out,
  953. char *peer_digest_out)
  954. {
  955. X509 *cert;
  956. unsigned int len;
  957. tor_assert(tls && tls->context);
  958. cert = tls->context->my_cert;
  959. if (cert) {
  960. X509_digest(cert, EVP_sha1(), (unsigned char*)my_digest_out, &len);
  961. if (len != DIGEST_LEN)
  962. return -1;
  963. }
  964. cert = SSL_get_peer_certificate(tls->ssl);
  965. if (cert) {
  966. X509_digest(cert, EVP_sha1(), (unsigned char*)peer_digest_out, &len);
  967. if (len != DIGEST_LEN)
  968. return -1;
  969. }
  970. return 0;
  971. }
  972. /** DOCDOC */
  973. crypto_pk_env_t *
  974. tor_tls_dup_private_key(tor_tls_t *tls)
  975. {
  976. return crypto_pk_dup_key(tls->context->key);
  977. }
  978. /** DOCDOC */
  979. char *
  980. tor_tls_encode_my_certificate(tor_tls_t *tls, size_t *size_out,
  981. int conn_cert)
  982. {
  983. unsigned char *result, *cp;
  984. int certlen;
  985. X509 *cert;
  986. tor_assert(tls && tls->context);
  987. cert = conn_cert ? tls->context->my_cert : tls->context->my_id_cert;
  988. tor_assert(cert);
  989. certlen = i2d_X509(cert, NULL);
  990. tor_assert(certlen >= 0);
  991. cp = result = tor_malloc(certlen);
  992. i2d_X509(cert, &cp);
  993. tor_assert(cp-result == certlen);
  994. *size_out = (size_t)certlen;
  995. return (char*) result;
  996. }
  997. /** Warn that a certificate lifetime extends through a certain range. */
  998. static void
  999. log_cert_lifetime(X509 *cert, const char *problem)
  1000. {
  1001. BIO *bio = NULL;
  1002. BUF_MEM *buf;
  1003. char *s1=NULL, *s2=NULL;
  1004. char mytime[33];
  1005. time_t now = time(NULL);
  1006. struct tm tm;
  1007. if (problem)
  1008. log_warn(LD_GENERAL,
  1009. "Certificate %s: is your system clock set incorrectly?",
  1010. problem);
  1011. if (!(bio = BIO_new(BIO_s_mem()))) {
  1012. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1013. }
  1014. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1015. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1016. goto end;
  1017. }
  1018. BIO_get_mem_ptr(bio, &buf);
  1019. s1 = tor_strndup(buf->data, buf->length);
  1020. (void)BIO_reset(bio);
  1021. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1022. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1023. goto end;
  1024. }
  1025. BIO_get_mem_ptr(bio, &buf);
  1026. s2 = tor_strndup(buf->data, buf->length);
  1027. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1028. log_warn(LD_GENERAL,
  1029. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1030. s1,s2,mytime);
  1031. end:
  1032. /* Not expected to get invoked */
  1033. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  1034. if (bio)
  1035. BIO_free(bio);
  1036. if (s1)
  1037. tor_free(s1);
  1038. if (s2)
  1039. tor_free(s2);
  1040. }
  1041. /** DOCDOC helper.
  1042. * cert_out needs to be freed. id_cert_out doesn't. */
  1043. static void
  1044. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1045. X509 **cert_out, X509 **id_cert_out)
  1046. {
  1047. X509 *cert = NULL, *id_cert = NULL;
  1048. STACK_OF(X509) *chain = NULL;
  1049. int num_in_chain, i;
  1050. *cert_out = *id_cert_out = NULL;
  1051. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1052. return;
  1053. *cert_out = cert;
  1054. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1055. return;
  1056. num_in_chain = sk_X509_num(chain);
  1057. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1058. * 2 means we're connecting (client-side), and it's both the link
  1059. * cert and the id_cert.
  1060. */
  1061. if (num_in_chain < 1) {
  1062. log_fn(severity,LD_PROTOCOL,
  1063. "Unexpected number of certificates in chain (%d)",
  1064. num_in_chain);
  1065. return;
  1066. }
  1067. for (i=0; i<num_in_chain; ++i) {
  1068. id_cert = sk_X509_value(chain, i);
  1069. if (X509_cmp(id_cert, cert) != 0)
  1070. break;
  1071. }
  1072. *id_cert_out = id_cert;
  1073. }
  1074. /** If the provided tls connection is authenticated and has a
  1075. * certificate that is currently valid and signed, then set
  1076. * *<b>identity_key</b> to the identity certificate's key and return
  1077. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1078. */
  1079. int
  1080. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1081. {
  1082. X509 *cert = NULL, *id_cert = NULL;
  1083. EVP_PKEY *id_pkey = NULL;
  1084. RSA *rsa;
  1085. int r = -1;
  1086. *identity_key = NULL;
  1087. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1088. if (!cert)
  1089. goto done;
  1090. if (!id_cert) {
  1091. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1092. goto done;
  1093. }
  1094. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1095. X509_verify(cert, id_pkey) <= 0) {
  1096. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1097. tls_log_errors(severity,"verifying certificate");
  1098. goto done;
  1099. }
  1100. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1101. if (!rsa)
  1102. goto done;
  1103. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1104. r = 0;
  1105. done:
  1106. if (cert)
  1107. X509_free(cert);
  1108. if (id_pkey)
  1109. EVP_PKEY_free(id_pkey);
  1110. /* This should never get invoked, but let's make sure in case OpenSSL
  1111. * acts unexpectedly. */
  1112. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  1113. return r;
  1114. }
  1115. #if 0
  1116. /** DOCDOC
  1117. *
  1118. * Returns 1 on "verification is done", 0 on "still need LINK_AUTH."
  1119. */
  1120. int
  1121. tor_tls_verify_certs_v2(int severity, tor_tls_t *tls,
  1122. const char *cert_str, size_t cert_len,
  1123. const char *id_cert_str, size_t id_cert_len,
  1124. crypto_pk_env_t **cert_key_out,
  1125. char *conn_cert_digest_out,
  1126. crypto_pk_env_t **id_key_out,
  1127. char *id_digest_out)
  1128. {
  1129. X509 *cert = NULL, *id_cert = NULL;
  1130. EVP_PKEY *id_pkey = NULL, *cert_pkey = NULL;
  1131. int free_id_cert = 0, peer_used_tls_cert = 0;
  1132. int r = -1;
  1133. tor_assert(cert_key_out);
  1134. tor_assert(conn_cert_digest_out);
  1135. tor_assert(id_key_out);
  1136. tor_assert(id_digest_out);
  1137. *cert_key_out = NULL;
  1138. if (cert_str && cert_len) {
  1139. /*XXXX020 warn on error. */
  1140. const unsigned char *cp = (const unsigned char*) cert_str;
  1141. cert = d2i_X509(NULL, &cp, cert_len);
  1142. }
  1143. if (id_cert_str && id_cert_len) {
  1144. /*XXXX020 warn on error. */
  1145. const unsigned char *cp = (const unsigned char*) id_cert_str;
  1146. id_cert = d2i_X509(NULL, &cp, id_cert_len);
  1147. if (id_cert)
  1148. free_id_cert = 1;
  1149. }
  1150. if (cert) {
  1151. int cmp = 0;
  1152. X509 *cert_tmp = SSL_get_peer_certificate(tls->ssl);
  1153. if (cert_tmp) {
  1154. peer_used_tls_cert = 1;
  1155. cmp = X509_cmp(cert, cert_tmp);
  1156. X509_free(cert_tmp);
  1157. }
  1158. if (cmp != 0) {
  1159. log_fn(severity, LD_PROTOCOL,
  1160. "Certificate in CERT cell didn't match TLS cert.");
  1161. goto done;
  1162. }
  1163. }
  1164. if (!cert || !id_cert) {
  1165. X509 *c=NULL, *id=NULL;
  1166. try_to_extract_certs_from_tls(severity, tls, &c, &id);
  1167. if (c) {
  1168. if (!cert)
  1169. cert = c;
  1170. else
  1171. X509_free(c);
  1172. }
  1173. if (id && !id_cert)
  1174. id_cert = id;
  1175. }
  1176. if (!id_cert || !cert)
  1177. goto done;
  1178. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1179. X509_verify(cert, id_pkey) <= 0) {
  1180. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1181. tls_log_errors(severity,"verifying certificate");
  1182. goto done;
  1183. }
  1184. if (!(*id_key_out = _crypto_new_pk_env_evp_pkey(id_pkey)))
  1185. goto done;
  1186. crypto_pk_get_digest(*id_key_out, id_digest_out);
  1187. if (!(cert_pkey = X509_get_pubkey(cert)))
  1188. goto done;
  1189. if (!(*cert_key_out = _crypto_new_pk_env_evp_pkey(cert_pkey)))
  1190. goto done;
  1191. {
  1192. unsigned int len = 0;
  1193. X509_digest(cert, EVP_sha1(), (unsigned char*)conn_cert_digest_out, &len);
  1194. tor_assert(len == DIGEST_LEN);
  1195. }
  1196. r = peer_used_tls_cert ? 1 : 0;
  1197. done:
  1198. if (cert)
  1199. X509_free(cert);
  1200. if (id_cert && free_id_cert)
  1201. X509_free(id_cert);
  1202. if (id_pkey)
  1203. EVP_PKEY_free(id_pkey);
  1204. if (cert_pkey)
  1205. EVP_PKEY_free(cert_pkey);
  1206. return r;
  1207. }
  1208. #endif
  1209. /** Check whether the certificate set on the connection <b>tls</b> is
  1210. * expired or not-yet-valid, give or take <b>tolerance</b>
  1211. * seconds. Return 0 for valid, -1 for failure.
  1212. *
  1213. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1214. */
  1215. int
  1216. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1217. {
  1218. time_t now, t;
  1219. X509 *cert;
  1220. int r = -1;
  1221. now = time(NULL);
  1222. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1223. goto done;
  1224. t = now + tolerance;
  1225. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1226. log_cert_lifetime(cert, "not yet valid");
  1227. goto done;
  1228. }
  1229. t = now - tolerance;
  1230. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1231. log_cert_lifetime(cert, "already expired");
  1232. goto done;
  1233. }
  1234. r = 0;
  1235. done:
  1236. if (cert)
  1237. X509_free(cert);
  1238. /* Not expected to get invoked */
  1239. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  1240. return r;
  1241. }
  1242. /** Return the number of bytes available for reading from <b>tls</b>.
  1243. */
  1244. int
  1245. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1246. {
  1247. tor_assert(tls);
  1248. return SSL_pending(tls->ssl);
  1249. }
  1250. /** If <b>tls</b> requires that the next write be of a particular size,
  1251. * return that size. Otherwise, return 0. */
  1252. size_t
  1253. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1254. {
  1255. return tls->wantwrite_n;
  1256. }
  1257. /** Sets n_read and n_written to the number of bytes read and written,
  1258. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1259. * function was called on <b>tls</b>. */
  1260. void
  1261. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1262. {
  1263. unsigned long r, w;
  1264. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1265. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1266. /* We are ok with letting these unsigned ints go "negative" here:
  1267. * If we wrapped around, this should still give us the right answer, unless
  1268. * we wrapped around by more than ULONG_MAX since the last time we called
  1269. * this function.
  1270. */
  1271. *n_read = (size_t)(r - tls->last_read_count);
  1272. *n_written = (size_t)(w - tls->last_write_count);
  1273. tls->last_read_count = r;
  1274. tls->last_write_count = w;
  1275. }
  1276. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1277. * errors, log an error message. */
  1278. void
  1279. _check_no_tls_errors(const char *fname, int line)
  1280. {
  1281. if (ERR_peek_error() == 0)
  1282. return;
  1283. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1284. tor_fix_source_file(fname), line);
  1285. tls_log_errors(LOG_WARN, NULL);
  1286. }
  1287. /**DOCDOC */
  1288. int
  1289. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1290. {
  1291. if (tls->isServer) {
  1292. #ifdef V2_HANDSHAKE_SERVER
  1293. return ! tls->wasV2Handshake;
  1294. #endif
  1295. } else {
  1296. #ifdef V2_HANDSHAKE_CLIENT
  1297. return ! tls->wasV2Handshake;
  1298. #endif
  1299. }
  1300. return 1;
  1301. }
  1302. #if SSL3_RANDOM_SIZE != TOR_TLS_RANDOM_LEN
  1303. #error "The TOR_TLS_RANDOM_LEN macro is defined incorrectly. That's a bug."
  1304. #endif
  1305. /** DOCDOC */
  1306. int
  1307. tor_tls_get_random_values(tor_tls_t *tls, char *client_random_out,
  1308. char *server_random_out)
  1309. {
  1310. tor_assert(tls && tls->ssl);
  1311. if (!tls->ssl->s3)
  1312. return -1;
  1313. memcpy(client_random_out, tls->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  1314. memcpy(server_random_out, tls->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  1315. return 0;
  1316. }
  1317. /** DOCDOC */
  1318. int
  1319. tor_tls_hmac_with_master_secret(tor_tls_t *tls, char *hmac_out,
  1320. const char *data, size_t data_len)
  1321. {
  1322. SSL_SESSION *s;
  1323. tor_assert(tls && tls->ssl);
  1324. if (!(s = SSL_get_session(tls->ssl)))
  1325. return -1;
  1326. if (s->master_key_length < 0)
  1327. return -1;
  1328. crypto_hmac_sha1(hmac_out,
  1329. (const char*)s->master_key,
  1330. (size_t)s->master_key_length,
  1331. data, data_len);
  1332. return 0;
  1333. }