tortls.c 40 KB

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