tortls.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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. #endif
  842. SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
  843. }
  844. }
  845. return r;
  846. }
  847. /** Client only: Renegotiate a TLS session. When finished, returns
  848. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  849. * TOR_TLS_WANTWRITE.
  850. */
  851. int
  852. tor_tls_renegotiate(tor_tls_t *tls)
  853. {
  854. int r;
  855. tor_assert(tls);
  856. /* We could do server-initiated renegotiation too, but that would be tricky.
  857. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  858. tor_assert(!tls->isServer);
  859. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  860. int r = SSL_renegotiate(tls->ssl);
  861. if (r <= 0) {
  862. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  863. "renegotiating", LOG_WARN);
  864. }
  865. tls->state = TOR_TLS_ST_RENEGOTIATE;
  866. }
  867. r = SSL_do_handshake(tls->ssl);
  868. if (r == 1) {
  869. tls->state = TOR_TLS_ST_OPEN;
  870. return TOR_TLS_DONE;
  871. } else
  872. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  873. "renegotiating handshake", LOG_WARN);
  874. }
  875. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  876. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  877. * or TOR_TLS_WANTWRITE.
  878. */
  879. int
  880. tor_tls_shutdown(tor_tls_t *tls)
  881. {
  882. int r, err;
  883. char buf[128];
  884. tor_assert(tls);
  885. tor_assert(tls->ssl);
  886. while (1) {
  887. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  888. /* If we've already called shutdown once to send a close message,
  889. * we read until the other side has closed too.
  890. */
  891. do {
  892. r = SSL_read(tls->ssl, buf, 128);
  893. } while (r>0);
  894. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  895. LOG_INFO);
  896. if (err == _TOR_TLS_ZERORETURN) {
  897. tls->state = TOR_TLS_ST_GOTCLOSE;
  898. /* fall through... */
  899. } else {
  900. return err;
  901. }
  902. }
  903. r = SSL_shutdown(tls->ssl);
  904. if (r == 1) {
  905. /* If shutdown returns 1, the connection is entirely closed. */
  906. tls->state = TOR_TLS_ST_CLOSED;
  907. return TOR_TLS_DONE;
  908. }
  909. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  910. LOG_INFO);
  911. if (err == _TOR_TLS_SYSCALL) {
  912. /* The underlying TCP connection closed while we were shutting down. */
  913. tls->state = TOR_TLS_ST_CLOSED;
  914. return TOR_TLS_DONE;
  915. } else if (err == _TOR_TLS_ZERORETURN) {
  916. /* The TLS connection says that it sent a shutdown record, but
  917. * isn't done shutting down yet. Make sure that this hasn't
  918. * happened before, then go back to the start of the function
  919. * and try to read.
  920. */
  921. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  922. tls->state == TOR_TLS_ST_SENTCLOSE) {
  923. log(LOG_WARN, LD_NET,
  924. "TLS returned \"half-closed\" value while already half-closed");
  925. return TOR_TLS_ERROR_MISC;
  926. }
  927. tls->state = TOR_TLS_ST_SENTCLOSE;
  928. /* fall through ... */
  929. } else {
  930. return err;
  931. }
  932. } /* end loop */
  933. }
  934. /** Return true iff this TLS connection is authenticated.
  935. */
  936. int
  937. tor_tls_peer_has_cert(tor_tls_t *tls)
  938. {
  939. X509 *cert;
  940. cert = SSL_get_peer_certificate(tls->ssl);
  941. tls_log_errors(LOG_WARN, "getting peer certificate");
  942. if (!cert)
  943. return 0;
  944. X509_free(cert);
  945. return 1;
  946. }
  947. /** DOCDOC */
  948. int
  949. tor_tls_get_cert_digests(tor_tls_t *tls,
  950. char *my_digest_out,
  951. char *peer_digest_out)
  952. {
  953. X509 *cert;
  954. unsigned int len;
  955. tor_assert(tls && tls->context);
  956. cert = tls->context->my_cert;
  957. if (cert) {
  958. X509_digest(cert, EVP_sha1(), (unsigned char*)my_digest_out, &len);
  959. if (len != DIGEST_LEN)
  960. return -1;
  961. }
  962. cert = SSL_get_peer_certificate(tls->ssl);
  963. if (cert) {
  964. X509_digest(cert, EVP_sha1(), (unsigned char*)peer_digest_out, &len);
  965. if (len != DIGEST_LEN)
  966. return -1;
  967. }
  968. return 0;
  969. }
  970. /** DOCDOC */
  971. crypto_pk_env_t *
  972. tor_tls_dup_private_key(tor_tls_t *tls)
  973. {
  974. return crypto_pk_dup_key(tls->context->key);
  975. }
  976. /** DOCDOC */
  977. char *
  978. tor_tls_encode_my_certificate(tor_tls_t *tls, size_t *size_out,
  979. int conn_cert)
  980. {
  981. unsigned char *result, *cp;
  982. int certlen;
  983. X509 *cert;
  984. tor_assert(tls && tls->context);
  985. cert = conn_cert ? tls->context->my_cert : tls->context->my_id_cert;
  986. tor_assert(cert);
  987. certlen = i2d_X509(cert, NULL);
  988. tor_assert(certlen >= 0);
  989. cp = result = tor_malloc(certlen);
  990. i2d_X509(cert, &cp);
  991. tor_assert(cp-result == certlen);
  992. *size_out = (size_t)certlen;
  993. return (char*) result;
  994. }
  995. /** Warn that a certificate lifetime extends through a certain range. */
  996. static void
  997. log_cert_lifetime(X509 *cert, const char *problem)
  998. {
  999. BIO *bio = NULL;
  1000. BUF_MEM *buf;
  1001. char *s1=NULL, *s2=NULL;
  1002. char mytime[33];
  1003. time_t now = time(NULL);
  1004. struct tm tm;
  1005. if (problem)
  1006. log_warn(LD_GENERAL,
  1007. "Certificate %s: is your system clock set incorrectly?",
  1008. problem);
  1009. if (!(bio = BIO_new(BIO_s_mem()))) {
  1010. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1011. }
  1012. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1013. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1014. goto end;
  1015. }
  1016. BIO_get_mem_ptr(bio, &buf);
  1017. s1 = tor_strndup(buf->data, buf->length);
  1018. (void)BIO_reset(bio);
  1019. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1020. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1021. goto end;
  1022. }
  1023. BIO_get_mem_ptr(bio, &buf);
  1024. s2 = tor_strndup(buf->data, buf->length);
  1025. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1026. log_warn(LD_GENERAL,
  1027. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1028. s1,s2,mytime);
  1029. end:
  1030. /* Not expected to get invoked */
  1031. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  1032. if (bio)
  1033. BIO_free(bio);
  1034. if (s1)
  1035. tor_free(s1);
  1036. if (s2)
  1037. tor_free(s2);
  1038. }
  1039. /** DOCDOC helper.
  1040. * cert_out needs to be freed. id_cert_out doesn't. */
  1041. static void
  1042. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1043. X509 **cert_out, X509 **id_cert_out)
  1044. {
  1045. X509 *cert = NULL, *id_cert = NULL;
  1046. STACK_OF(X509) *chain = NULL;
  1047. int num_in_chain, i;
  1048. *cert_out = *id_cert_out = NULL;
  1049. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1050. return;
  1051. *cert_out = cert;
  1052. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1053. return;
  1054. num_in_chain = sk_X509_num(chain);
  1055. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1056. * 2 means we're connecting (client-side), and it's both the link
  1057. * cert and the id_cert.
  1058. */
  1059. if (num_in_chain < 1) {
  1060. log_fn(severity,LD_PROTOCOL,
  1061. "Unexpected number of certificates in chain (%d)",
  1062. num_in_chain);
  1063. return;
  1064. }
  1065. for (i=0; i<num_in_chain; ++i) {
  1066. id_cert = sk_X509_value(chain, i);
  1067. if (X509_cmp(id_cert, cert) != 0)
  1068. break;
  1069. }
  1070. *id_cert_out = id_cert;
  1071. }
  1072. /** If the provided tls connection is authenticated and has a
  1073. * certificate that is currently valid and signed, then set
  1074. * *<b>identity_key</b> to the identity certificate's key and return
  1075. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1076. */
  1077. int
  1078. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1079. {
  1080. X509 *cert = NULL, *id_cert = NULL;
  1081. EVP_PKEY *id_pkey = NULL;
  1082. RSA *rsa;
  1083. int r = -1;
  1084. *identity_key = NULL;
  1085. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1086. if (!cert)
  1087. goto done;
  1088. if (!id_cert) {
  1089. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1090. goto done;
  1091. }
  1092. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1093. X509_verify(cert, id_pkey) <= 0) {
  1094. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1095. tls_log_errors(severity,"verifying certificate");
  1096. goto done;
  1097. }
  1098. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1099. if (!rsa)
  1100. goto done;
  1101. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1102. r = 0;
  1103. done:
  1104. if (cert)
  1105. X509_free(cert);
  1106. if (id_pkey)
  1107. EVP_PKEY_free(id_pkey);
  1108. /* This should never get invoked, but let's make sure in case OpenSSL
  1109. * acts unexpectedly. */
  1110. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  1111. return r;
  1112. }
  1113. #if 0
  1114. /** DOCDOC
  1115. *
  1116. * Returns 1 on "verification is done", 0 on "still need LINK_AUTH."
  1117. */
  1118. int
  1119. tor_tls_verify_certs_v2(int severity, tor_tls_t *tls,
  1120. const char *cert_str, size_t cert_len,
  1121. const char *id_cert_str, size_t id_cert_len,
  1122. crypto_pk_env_t **cert_key_out,
  1123. char *conn_cert_digest_out,
  1124. crypto_pk_env_t **id_key_out,
  1125. char *id_digest_out)
  1126. {
  1127. X509 *cert = NULL, *id_cert = NULL;
  1128. EVP_PKEY *id_pkey = NULL, *cert_pkey = NULL;
  1129. int free_id_cert = 0, peer_used_tls_cert = 0;
  1130. int r = -1;
  1131. tor_assert(cert_key_out);
  1132. tor_assert(conn_cert_digest_out);
  1133. tor_assert(id_key_out);
  1134. tor_assert(id_digest_out);
  1135. *cert_key_out = NULL;
  1136. if (cert_str && cert_len) {
  1137. /*XXXX020 warn on error. */
  1138. const unsigned char *cp = (const unsigned char*) cert_str;
  1139. cert = d2i_X509(NULL, &cp, cert_len);
  1140. }
  1141. if (id_cert_str && id_cert_len) {
  1142. /*XXXX020 warn on error. */
  1143. const unsigned char *cp = (const unsigned char*) id_cert_str;
  1144. id_cert = d2i_X509(NULL, &cp, id_cert_len);
  1145. if (id_cert)
  1146. free_id_cert = 1;
  1147. }
  1148. if (cert) {
  1149. int cmp = 0;
  1150. X509 *cert_tmp = SSL_get_peer_certificate(tls->ssl);
  1151. if (cert_tmp) {
  1152. peer_used_tls_cert = 1;
  1153. cmp = X509_cmp(cert, cert_tmp);
  1154. X509_free(cert_tmp);
  1155. }
  1156. if (cmp != 0) {
  1157. log_fn(severity, LD_PROTOCOL,
  1158. "Certificate in CERT cell didn't match TLS cert.");
  1159. goto done;
  1160. }
  1161. }
  1162. if (!cert || !id_cert) {
  1163. X509 *c=NULL, *id=NULL;
  1164. try_to_extract_certs_from_tls(severity, tls, &c, &id);
  1165. if (c) {
  1166. if (!cert)
  1167. cert = c;
  1168. else
  1169. X509_free(c);
  1170. }
  1171. if (id && !id_cert)
  1172. id_cert = id;
  1173. }
  1174. if (!id_cert || !cert)
  1175. goto done;
  1176. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1177. X509_verify(cert, id_pkey) <= 0) {
  1178. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1179. tls_log_errors(severity,"verifying certificate");
  1180. goto done;
  1181. }
  1182. if (!(*id_key_out = _crypto_new_pk_env_evp_pkey(id_pkey)))
  1183. goto done;
  1184. crypto_pk_get_digest(*id_key_out, id_digest_out);
  1185. if (!(cert_pkey = X509_get_pubkey(cert)))
  1186. goto done;
  1187. if (!(*cert_key_out = _crypto_new_pk_env_evp_pkey(cert_pkey)))
  1188. goto done;
  1189. {
  1190. unsigned int len = 0;
  1191. X509_digest(cert, EVP_sha1(), (unsigned char*)conn_cert_digest_out, &len);
  1192. tor_assert(len == DIGEST_LEN);
  1193. }
  1194. r = peer_used_tls_cert ? 1 : 0;
  1195. done:
  1196. if (cert)
  1197. X509_free(cert);
  1198. if (id_cert && free_id_cert)
  1199. X509_free(id_cert);
  1200. if (id_pkey)
  1201. EVP_PKEY_free(id_pkey);
  1202. if (cert_pkey)
  1203. EVP_PKEY_free(cert_pkey);
  1204. return r;
  1205. }
  1206. #endif
  1207. /** Check whether the certificate set on the connection <b>tls</b> is
  1208. * expired or not-yet-valid, give or take <b>tolerance</b>
  1209. * seconds. Return 0 for valid, -1 for failure.
  1210. *
  1211. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1212. */
  1213. int
  1214. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1215. {
  1216. time_t now, t;
  1217. X509 *cert;
  1218. int r = -1;
  1219. now = time(NULL);
  1220. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1221. goto done;
  1222. t = now + tolerance;
  1223. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1224. log_cert_lifetime(cert, "not yet valid");
  1225. goto done;
  1226. }
  1227. t = now - tolerance;
  1228. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1229. log_cert_lifetime(cert, "already expired");
  1230. goto done;
  1231. }
  1232. r = 0;
  1233. done:
  1234. if (cert)
  1235. X509_free(cert);
  1236. /* Not expected to get invoked */
  1237. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  1238. return r;
  1239. }
  1240. /** Return the number of bytes available for reading from <b>tls</b>.
  1241. */
  1242. int
  1243. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1244. {
  1245. tor_assert(tls);
  1246. return SSL_pending(tls->ssl);
  1247. }
  1248. /** If <b>tls</b> requires that the next write be of a particular size,
  1249. * return that size. Otherwise, return 0. */
  1250. size_t
  1251. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1252. {
  1253. return tls->wantwrite_n;
  1254. }
  1255. /** Sets n_read and n_written to the number of bytes read and written,
  1256. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1257. * function was called on <b>tls</b>. */
  1258. void
  1259. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1260. {
  1261. unsigned long r, w;
  1262. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1263. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1264. /* We are ok with letting these unsigned ints go "negative" here:
  1265. * If we wrapped around, this should still give us the right answer, unless
  1266. * we wrapped around by more than ULONG_MAX since the last time we called
  1267. * this function.
  1268. */
  1269. *n_read = (size_t)(r - tls->last_read_count);
  1270. *n_written = (size_t)(w - tls->last_write_count);
  1271. tls->last_read_count = r;
  1272. tls->last_write_count = w;
  1273. }
  1274. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1275. * errors, log an error message. */
  1276. void
  1277. _check_no_tls_errors(const char *fname, int line)
  1278. {
  1279. if (ERR_peek_error() == 0)
  1280. return;
  1281. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1282. tor_fix_source_file(fname), line);
  1283. tls_log_errors(LOG_WARN, NULL);
  1284. }
  1285. /**DOCDOC */
  1286. int
  1287. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1288. {
  1289. if (tls->isServer) {
  1290. #ifdef V2_HANDSHAKE_SERVER
  1291. return ! tls->wasV2Handshake;
  1292. #endif
  1293. } else {
  1294. #ifdef V2_HANDSHAKE_CLIENT
  1295. return ! tls->wasV2Handshake;
  1296. #endif
  1297. }
  1298. return 1;
  1299. }
  1300. #if SSL3_RANDOM_SIZE != TOR_TLS_RANDOM_LEN
  1301. #error "The TOR_TLS_RANDOM_LEN macro is defined incorrectly. That's a bug."
  1302. #endif
  1303. /** DOCDOC */
  1304. int
  1305. tor_tls_get_random_values(tor_tls_t *tls, char *client_random_out,
  1306. char *server_random_out)
  1307. {
  1308. tor_assert(tls && tls->ssl);
  1309. if (!tls->ssl->s3)
  1310. return -1;
  1311. memcpy(client_random_out, tls->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  1312. memcpy(server_random_out, tls->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  1313. return 0;
  1314. }
  1315. /** DOCDOC */
  1316. int
  1317. tor_tls_hmac_with_master_secret(tor_tls_t *tls, char *hmac_out,
  1318. const char *data, size_t data_len)
  1319. {
  1320. SSL_SESSION *s;
  1321. tor_assert(tls && tls->ssl);
  1322. if (!(s = SSL_get_session(tls->ssl)))
  1323. return -1;
  1324. if (s->master_key_length < 0)
  1325. return -1;
  1326. crypto_hmac_sha1(hmac_out,
  1327. (const char*)s->master_key,
  1328. (size_t)s->master_key_length,
  1329. data, data_len);
  1330. return 0;
  1331. }