tortls.c 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file tortls.c
  7. * \brief Wrapper functions to present a consistent interface to
  8. * TLS, SSL, and X.509 functions from OpenSSL.
  9. **/
  10. /* (Unlike other tor functions, these
  11. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  12. * functions and variables.)
  13. */
  14. #include "orconfig.h"
  15. #include <assert.h>
  16. #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  17. #ifndef _WIN32_WINNT
  18. #define _WIN32_WINNT 0x0501
  19. #endif
  20. #define WIN32_LEAN_AND_MEAN
  21. #if defined(_MSC_VER) && (_MSC_VER < 1300)
  22. #include <winsock.h>
  23. #else
  24. #include <winsock2.h>
  25. #include <ws2tcpip.h>
  26. #endif
  27. #endif
  28. #ifdef __GNUC__
  29. #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  30. #endif
  31. #if __GNUC__ && GCC_VERSION >= 402
  32. #if GCC_VERSION >= 406
  33. #pragma GCC diagnostic push
  34. #endif
  35. /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
  36. * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
  37. #pragma GCC diagnostic ignored "-Wredundant-decls"
  38. #endif
  39. #include <openssl/ssl.h>
  40. #include <openssl/ssl3.h>
  41. #include <openssl/err.h>
  42. #include <openssl/tls1.h>
  43. #include <openssl/asn1.h>
  44. #include <openssl/bio.h>
  45. #include <openssl/opensslv.h>
  46. #include <openssl/bn.h>
  47. #include <openssl/rsa.h>
  48. #if __GNUC__ && GCC_VERSION >= 402
  49. #if GCC_VERSION >= 406
  50. #pragma GCC diagnostic pop
  51. #else
  52. #pragma GCC diagnostic warning "-Wredundant-decls"
  53. #endif
  54. #endif
  55. #ifdef USE_BUFFEREVENTS
  56. #include <event2/bufferevent_ssl.h>
  57. #include <event2/buffer.h>
  58. #include <event2/event.h>
  59. #include "compat_libevent.h"
  60. #endif
  61. #include "crypto.h"
  62. #include "tortls.h"
  63. #include "util.h"
  64. #include "torlog.h"
  65. #include "container.h"
  66. #include <string.h>
  67. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
  68. #error "We require OpenSSL >= 0.9.8"
  69. #endif
  70. /* Enable the "v2" TLS handshake.
  71. */
  72. #define V2_HANDSHAKE_SERVER
  73. #define V2_HANDSHAKE_CLIENT
  74. /* Copied from or.h */
  75. #define LEGAL_NICKNAME_CHARACTERS \
  76. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  77. /** How long do identity certificates live? (sec) */
  78. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  79. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  80. #if (OPENSSL_VERSION_NUMBER < OPENSSL_V(0,9,8,'s') || \
  81. (OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(0,9,9) && \
  82. OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')))
  83. /* This is a version of OpenSSL before 0.9.8s/1.0.0f. It does not have
  84. * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
  85. * SSL3 safely at the same time.
  86. */
  87. #define DISABLE_SSL3_HANDSHAKE
  88. #endif
  89. /* We redefine these so that we can run correctly even if the vendor gives us
  90. * a version of OpenSSL that does not match its header files. (Apple: I am
  91. * looking at you.)
  92. */
  93. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  94. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  95. #endif
  96. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  97. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  98. #endif
  99. /** Does the run-time openssl version look like we need
  100. * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  101. static int use_unsafe_renegotiation_op = 0;
  102. /** Does the run-time openssl version look like we need
  103. * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  104. static int use_unsafe_renegotiation_flag = 0;
  105. /** Structure that we use for a single certificate. */
  106. struct tor_x509_cert_t {
  107. X509 *cert;
  108. uint8_t *encoded;
  109. size_t encoded_len;
  110. unsigned pkey_digests_set : 1;
  111. digests_t cert_digests;
  112. digests_t pkey_digests;
  113. };
  114. /** Holds a SSL_CTX object and related state used to configure TLS
  115. * connections.
  116. */
  117. typedef struct tor_tls_context_t {
  118. int refcnt;
  119. SSL_CTX *ctx;
  120. tor_x509_cert_t *my_link_cert;
  121. tor_x509_cert_t *my_id_cert;
  122. tor_x509_cert_t *my_auth_cert;
  123. crypto_pk_t *link_key;
  124. crypto_pk_t *auth_key;
  125. } tor_tls_context_t;
  126. /** Return values for tor_tls_classify_client_ciphers.
  127. *
  128. * @{
  129. */
  130. /** An error occurred when examining the client ciphers */
  131. #define CIPHERS_ERR -1
  132. /** The client cipher list indicates that a v1 handshake was in use. */
  133. #define CIPHERS_V1 1
  134. /** The client cipher list indicates that the client is using the v2 or the
  135. * v3 handshake, but that it is (probably!) lying about what ciphers it
  136. * supports */
  137. #define CIPHERS_V2 2
  138. /** The client cipher list indicates that the client is using the v2 or the
  139. * v3 handshake, and that it is telling the truth about what ciphers it
  140. * supports */
  141. #define CIPHERS_UNRESTRICTED 3
  142. /** @} */
  143. #define TOR_TLS_MAGIC 0x71571571
  144. typedef enum {
  145. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  146. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  147. TOR_TLS_ST_BUFFEREVENT
  148. } tor_tls_state_t;
  149. #define tor_tls_state_bitfield_t ENUM_BF(tor_tls_state_t)
  150. /** Holds a SSL object and its associated data. Members are only
  151. * accessed from within tortls.c.
  152. */
  153. struct tor_tls_t {
  154. uint32_t magic;
  155. tor_tls_context_t *context; /** A link to the context object for this tls. */
  156. SSL *ssl; /**< An OpenSSL SSL object. */
  157. int socket; /**< The underlying file descriptor for this TLS connection. */
  158. char *address; /**< An address to log when describing this connection. */
  159. tor_tls_state_bitfield_t state : 3; /**< The current SSL state,
  160. * depending on which operations
  161. * have completed successfully. */
  162. unsigned int isServer:1; /**< True iff this is a server-side connection */
  163. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  164. * this connection used the updated version
  165. * of the connection protocol (client sends
  166. * different cipher list, server sends only
  167. * one certificate). */
  168. /** True iff we should call negotiated_callback when we're done reading. */
  169. unsigned int got_renegotiate:1;
  170. /** Return value from tor_tls_classify_client_ciphers, or 0 if we haven't
  171. * called that function yet. */
  172. int8_t client_cipher_list_type;
  173. /** Incremented every time we start the server side of a handshake. */
  174. uint8_t server_handshake_count;
  175. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  176. * time. */
  177. /** Last values retrieved from BIO_number_read()/write(); see
  178. * tor_tls_get_n_raw_bytes() for usage.
  179. */
  180. unsigned long last_write_count;
  181. unsigned long last_read_count;
  182. /** If set, a callback to invoke whenever the client tries to renegotiate
  183. * the handshake. */
  184. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  185. /** Argument to pass to negotiated_callback. */
  186. void *callback_arg;
  187. };
  188. #ifdef V2_HANDSHAKE_CLIENT
  189. /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
  190. * in client mode into advertising the ciphers we want. See
  191. * rectify_client_ciphers() for details. */
  192. static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
  193. /** A stack of SSL_CIPHER objects, some real, some fake.
  194. * See rectify_client_ciphers() for details. */
  195. static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
  196. #endif
  197. /** The ex_data index in which we store a pointer to an SSL object's
  198. * corresponding tor_tls_t object. */
  199. static int tor_tls_object_ex_data_index = -1;
  200. /** Helper: Allocate tor_tls_object_ex_data_index. */
  201. static void
  202. tor_tls_allocate_tor_tls_object_ex_data_index(void)
  203. {
  204. if (tor_tls_object_ex_data_index == -1) {
  205. tor_tls_object_ex_data_index =
  206. SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  207. tor_assert(tor_tls_object_ex_data_index != -1);
  208. }
  209. }
  210. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  211. * pointer. */
  212. static INLINE tor_tls_t *
  213. tor_tls_get_by_ssl(const SSL *ssl)
  214. {
  215. tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  216. if (result)
  217. tor_assert(result->magic == TOR_TLS_MAGIC);
  218. return result;
  219. }
  220. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  221. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  222. static X509* tor_tls_create_certificate(crypto_pk_t *rsa,
  223. crypto_pk_t *rsa_sign,
  224. const char *cname,
  225. const char *cname_sign,
  226. unsigned int cert_lifetime);
  227. static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  228. crypto_pk_t *identity,
  229. unsigned int key_lifetime,
  230. unsigned int flags,
  231. int is_client);
  232. static tor_tls_context_t *tor_tls_context_new(crypto_pk_t *identity,
  233. unsigned int key_lifetime,
  234. unsigned int flags,
  235. int is_client);
  236. static int check_cert_lifetime_internal(int severity, const X509 *cert,
  237. int past_tolerance, int future_tolerance);
  238. /** Global TLS contexts. We keep them here because nobody else needs
  239. * to touch them.
  240. *
  241. * @{ */
  242. static tor_tls_context_t *server_tls_context = NULL;
  243. static tor_tls_context_t *client_tls_context = NULL;
  244. /**@}*/
  245. /** True iff tor_tls_init() has been called. */
  246. static int tls_library_is_initialized = 0;
  247. /* Module-internal error codes. */
  248. #define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
  249. #define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
  250. /** Write a description of the current state of <b>tls</b> into the
  251. * <b>sz</b>-byte buffer at <b>buf</b>. */
  252. void
  253. tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
  254. {
  255. const char *ssl_state;
  256. const char *tortls_state;
  257. if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
  258. strlcpy(buf, "(No SSL object)", sz);
  259. return;
  260. }
  261. ssl_state = SSL_state_string_long(tls->ssl);
  262. switch (tls->state) {
  263. #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
  264. CASE(HANDSHAKE);
  265. CASE(OPEN);
  266. CASE(GOTCLOSE);
  267. CASE(SENTCLOSE);
  268. CASE(CLOSED);
  269. CASE(RENEGOTIATE);
  270. #undef CASE
  271. case TOR_TLS_ST_BUFFEREVENT:
  272. tortls_state = "";
  273. break;
  274. default:
  275. tortls_state = " in unknown TLS state";
  276. break;
  277. }
  278. tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
  279. }
  280. /** Log a single error <b>err</b> as returned by ERR_get_error(), which was
  281. * received while performing an operation <b>doing</b> on <b>tls</b>. Log
  282. * the message at <b>severity</b>, in log domain <b>domain</b>. */
  283. void
  284. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  285. int severity, int domain, const char *doing)
  286. {
  287. const char *state = NULL, *addr;
  288. const char *msg, *lib, *func;
  289. state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
  290. addr = tls ? tls->address : NULL;
  291. /* Some errors are known-benign, meaning they are the fault of the other
  292. * side of the connection. The caller doesn't know this, so override the
  293. * priority for those cases. */
  294. switch (ERR_GET_REASON(err)) {
  295. case SSL_R_HTTP_REQUEST:
  296. case SSL_R_HTTPS_PROXY_REQUEST:
  297. case SSL_R_RECORD_LENGTH_MISMATCH:
  298. case SSL_R_RECORD_TOO_LARGE:
  299. case SSL_R_UNKNOWN_PROTOCOL:
  300. case SSL_R_UNSUPPORTED_PROTOCOL:
  301. severity = LOG_INFO;
  302. break;
  303. default:
  304. break;
  305. }
  306. msg = (const char*)ERR_reason_error_string(err);
  307. lib = (const char*)ERR_lib_error_string(err);
  308. func = (const char*)ERR_func_error_string(err);
  309. if (!msg) msg = "(null)";
  310. if (!lib) lib = "(null)";
  311. if (!func) func = "(null)";
  312. if (doing) {
  313. tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  314. doing, addr?" with ":"", addr?addr:"",
  315. msg, lib, func, state);
  316. } else {
  317. tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  318. addr?" with ":"", addr?addr:"",
  319. msg, lib, func, state);
  320. }
  321. }
  322. /** Log all pending tls errors at level <b>severity</b> in log domain
  323. * <b>domain</b>. Use <b>doing</b> to describe our current activities.
  324. */
  325. static void
  326. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  327. {
  328. unsigned long err;
  329. while ((err = ERR_get_error()) != 0) {
  330. tor_tls_log_one_error(tls, err, severity, domain, doing);
  331. }
  332. }
  333. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  334. * code. */
  335. static int
  336. tor_errno_to_tls_error(int e)
  337. {
  338. switch (e) {
  339. case SOCK_ERRNO(ECONNRESET): // most common
  340. return TOR_TLS_ERROR_CONNRESET;
  341. case SOCK_ERRNO(ETIMEDOUT):
  342. return TOR_TLS_ERROR_TIMEOUT;
  343. case SOCK_ERRNO(EHOSTUNREACH):
  344. case SOCK_ERRNO(ENETUNREACH):
  345. return TOR_TLS_ERROR_NO_ROUTE;
  346. case SOCK_ERRNO(ECONNREFUSED):
  347. return TOR_TLS_ERROR_CONNREFUSED; // least common
  348. default:
  349. return TOR_TLS_ERROR_MISC;
  350. }
  351. }
  352. /** Given a TOR_TLS_* error code, return a string equivalent. */
  353. const char *
  354. tor_tls_err_to_string(int err)
  355. {
  356. if (err >= 0)
  357. return "[Not an error.]";
  358. switch (err) {
  359. case TOR_TLS_ERROR_MISC: return "misc error";
  360. case TOR_TLS_ERROR_IO: return "unexpected close";
  361. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  362. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  363. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  364. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  365. case TOR_TLS_CLOSE: return "closed";
  366. case TOR_TLS_WANTREAD: return "want to read";
  367. case TOR_TLS_WANTWRITE: return "want to write";
  368. default: return "(unknown error code)";
  369. }
  370. }
  371. #define CATCH_SYSCALL 1
  372. #define CATCH_ZERO 2
  373. /** Given a TLS object and the result of an SSL_* call, use
  374. * SSL_get_error to determine whether an error has occurred, and if so
  375. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  376. * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
  377. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  378. * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
  379. *
  380. * If an error has occurred, log it at level <b>severity</b> and describe the
  381. * current action as <b>doing</b>.
  382. */
  383. static int
  384. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  385. const char *doing, int severity, int domain)
  386. {
  387. int err = SSL_get_error(tls->ssl, r);
  388. int tor_error = TOR_TLS_ERROR_MISC;
  389. switch (err) {
  390. case SSL_ERROR_NONE:
  391. return TOR_TLS_DONE;
  392. case SSL_ERROR_WANT_READ:
  393. return TOR_TLS_WANTREAD;
  394. case SSL_ERROR_WANT_WRITE:
  395. return TOR_TLS_WANTWRITE;
  396. case SSL_ERROR_SYSCALL:
  397. if (extra&CATCH_SYSCALL)
  398. return TOR_TLS_SYSCALL_;
  399. if (r == 0) {
  400. tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  401. doing, SSL_state_string_long(tls->ssl));
  402. tor_error = TOR_TLS_ERROR_IO;
  403. } else {
  404. int e = tor_socket_errno(tls->socket);
  405. tor_log(severity, LD_NET,
  406. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  407. doing, e, tor_socket_strerror(e),
  408. SSL_state_string_long(tls->ssl));
  409. tor_error = tor_errno_to_tls_error(e);
  410. }
  411. tls_log_errors(tls, severity, domain, doing);
  412. return tor_error;
  413. case SSL_ERROR_ZERO_RETURN:
  414. if (extra&CATCH_ZERO)
  415. return TOR_TLS_ZERORETURN_;
  416. tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
  417. doing, SSL_state_string_long(tls->ssl));
  418. tls_log_errors(tls, severity, domain, doing);
  419. return TOR_TLS_CLOSE;
  420. default:
  421. tls_log_errors(tls, severity, domain, doing);
  422. return TOR_TLS_ERROR_MISC;
  423. }
  424. }
  425. /** Initialize OpenSSL, unless it has already been initialized.
  426. */
  427. static void
  428. tor_tls_init(void)
  429. {
  430. check_no_tls_errors();
  431. if (!tls_library_is_initialized) {
  432. long version;
  433. SSL_library_init();
  434. SSL_load_error_strings();
  435. version = SSLeay();
  436. /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  437. * here, but without thinking too hard about it: it turns out that the
  438. * flag in question needed to be set at the last minute, and that it
  439. * conflicted with an existing flag number that had already been added
  440. * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
  441. * the flag with an option and (it seems) broke anything that used
  442. * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
  443. * and we mustn't use the SSL3_FLAGS option with anything besides
  444. * OpenSSL 0.9.8l.
  445. *
  446. * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
  447. * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
  448. * set option 0x00040000L everywhere.
  449. *
  450. * No, we can't simply detect whether the flag or the option is present
  451. * in the headers at build-time: some vendors (notably Apple) like to
  452. * leave their headers out of sync with their libraries.
  453. *
  454. * Yes, it _is_ almost as if the OpenSSL developers decided that no
  455. * program should be allowed to use renegotiation unless it first passed
  456. * a test of intelligence and determination.
  457. */
  458. if (version > OPENSSL_V(0,9,8,'k') && version <= OPENSSL_V(0,9,8,'l')) {
  459. log_info(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l, but "
  460. "some vendors have backported renegotiation code from "
  461. "0.9.8m without updating the version number. "
  462. "I will try SSL3_FLAGS and SSL_OP to enable renegotation.",
  463. SSLeay_version(SSLEAY_VERSION));
  464. use_unsafe_renegotiation_flag = 1;
  465. use_unsafe_renegotiation_op = 1;
  466. } else if (version > OPENSSL_V(0,9,8,'l')) {
  467. log_info(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
  468. "I will try SSL_OP to enable renegotiation",
  469. SSLeay_version(SSLEAY_VERSION));
  470. use_unsafe_renegotiation_op = 1;
  471. } else if (version <= OPENSSL_V(0,9,8,'k')) {
  472. log_info(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
  473. "0.9.8l, but some vendors have backported 0.9.8l's "
  474. "renegotiation code to earlier versions, and some have "
  475. "backported the code from 0.9.8m or 0.9.8n. I'll set both "
  476. "SSL3_FLAGS and SSL_OP just to be safe.",
  477. SSLeay_version(SSLEAY_VERSION), version);
  478. use_unsafe_renegotiation_flag = 1;
  479. use_unsafe_renegotiation_op = 1;
  480. } else {
  481. /* this is dead code, yes? */
  482. log_info(LD_GENERAL, "OpenSSL %s has version %lx",
  483. SSLeay_version(SSLEAY_VERSION), version);
  484. }
  485. #if (SIZEOF_VOID_P >= 8 && \
  486. !defined(OPENSSL_NO_EC) && \
  487. OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
  488. if (version >= OPENSSL_V_SERIES(1,0,1)) {
  489. /* Warn if we could *almost* be running with much faster ECDH.
  490. If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
  491. don't have one of the built-in __uint128-based speedups, we are
  492. just one build operation away from an accelerated handshake.
  493. (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
  494. doing this test, but that gives compile-time options, not runtime
  495. behavior.)
  496. */
  497. EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  498. const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
  499. const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
  500. const int warn = (m == EC_GFp_simple_method() ||
  501. m == EC_GFp_mont_method() ||
  502. m == EC_GFp_nist_method());
  503. EC_KEY_free(key);
  504. if (warn)
  505. log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
  506. "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
  507. "that apparently lacks accelerated support for the NIST "
  508. "P-224 and P-256 groups. Building openssl with such "
  509. "support (using the enable-ec_nistp_64_gcc_128 option "
  510. "when configuring it) would make ECDH much faster.");
  511. }
  512. #endif
  513. tor_tls_allocate_tor_tls_object_ex_data_index();
  514. tls_library_is_initialized = 1;
  515. }
  516. }
  517. /** Free all global TLS structures. */
  518. void
  519. tor_tls_free_all(void)
  520. {
  521. check_no_tls_errors();
  522. if (server_tls_context) {
  523. tor_tls_context_t *ctx = server_tls_context;
  524. server_tls_context = NULL;
  525. tor_tls_context_decref(ctx);
  526. }
  527. if (client_tls_context) {
  528. tor_tls_context_t *ctx = client_tls_context;
  529. client_tls_context = NULL;
  530. tor_tls_context_decref(ctx);
  531. }
  532. #ifdef V2_HANDSHAKE_CLIENT
  533. if (CLIENT_CIPHER_DUMMIES)
  534. tor_free(CLIENT_CIPHER_DUMMIES);
  535. if (CLIENT_CIPHER_STACK)
  536. sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
  537. #endif
  538. }
  539. /** We need to give OpenSSL a callback to verify certificates. This is
  540. * it: We always accept peer certs and complete the handshake. We
  541. * don't validate them until later.
  542. */
  543. static int
  544. always_accept_verify_cb(int preverify_ok,
  545. X509_STORE_CTX *x509_ctx)
  546. {
  547. (void) preverify_ok;
  548. (void) x509_ctx;
  549. return 1;
  550. }
  551. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  552. static X509_NAME *
  553. tor_x509_name_new(const char *cname)
  554. {
  555. int nid;
  556. X509_NAME *name;
  557. if (!(name = X509_NAME_new()))
  558. return NULL;
  559. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  560. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  561. (unsigned char*)cname, -1, -1, 0)))
  562. goto error;
  563. return name;
  564. error:
  565. X509_NAME_free(name);
  566. return NULL;
  567. }
  568. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  569. * signed by the private key <b>rsa_sign</b>. The commonName of the
  570. * certificate will be <b>cname</b>; the commonName of the issuer will be
  571. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
  572. * seconds, starting from some time in the past.
  573. *
  574. * Return a certificate on success, NULL on failure.
  575. */
  576. static X509 *
  577. tor_tls_create_certificate(crypto_pk_t *rsa,
  578. crypto_pk_t *rsa_sign,
  579. const char *cname,
  580. const char *cname_sign,
  581. unsigned int cert_lifetime)
  582. {
  583. /* OpenSSL generates self-signed certificates with random 64-bit serial
  584. * numbers, so let's do that too. */
  585. #define SERIAL_NUMBER_SIZE 8
  586. time_t start_time, end_time;
  587. BIGNUM *serial_number = NULL;
  588. unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
  589. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  590. X509 *x509 = NULL;
  591. X509_NAME *name = NULL, *name_issuer=NULL;
  592. tor_tls_init();
  593. /* Make sure we're part-way through the certificate lifetime, rather
  594. * than having it start right now. Don't choose quite uniformly, since
  595. * then we might pick a time where we're about to expire. Lastly, be
  596. * sure to start on a day boundary. */
  597. start_time = time(NULL) - crypto_rand_int(cert_lifetime) + 2*24*3600;
  598. start_time -= start_time % (24*3600);
  599. tor_assert(rsa);
  600. tor_assert(cname);
  601. tor_assert(rsa_sign);
  602. tor_assert(cname_sign);
  603. if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
  604. goto error;
  605. if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
  606. goto error;
  607. if (!(x509 = X509_new()))
  608. goto error;
  609. if (!(X509_set_version(x509, 2)))
  610. goto error;
  611. { /* our serial number is 8 random bytes. */
  612. if (crypto_rand((char *)serial_tmp, sizeof(serial_tmp)) < 0)
  613. goto error;
  614. if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
  615. goto error;
  616. if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
  617. goto error;
  618. }
  619. if (!(name = tor_x509_name_new(cname)))
  620. goto error;
  621. if (!(X509_set_subject_name(x509, name)))
  622. goto error;
  623. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  624. goto error;
  625. if (!(X509_set_issuer_name(x509, name_issuer)))
  626. goto error;
  627. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  628. goto error;
  629. end_time = start_time + cert_lifetime;
  630. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  631. goto error;
  632. if (!X509_set_pubkey(x509, pkey))
  633. goto error;
  634. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  635. goto error;
  636. goto done;
  637. error:
  638. if (x509) {
  639. X509_free(x509);
  640. x509 = NULL;
  641. }
  642. done:
  643. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  644. if (sign_pkey)
  645. EVP_PKEY_free(sign_pkey);
  646. if (pkey)
  647. EVP_PKEY_free(pkey);
  648. if (serial_number)
  649. BN_clear_free(serial_number);
  650. if (name)
  651. X509_NAME_free(name);
  652. if (name_issuer)
  653. X509_NAME_free(name_issuer);
  654. return x509;
  655. #undef SERIAL_NUMBER_SIZE
  656. }
  657. /** List of ciphers that servers should select from when the client might be
  658. * claiming extra unsupported ciphers in order to avoid fingerprinting. */
  659. #define SERVER_CIPHER_LIST \
  660. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  661. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  662. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  663. /** List of ciphers that servers should select from when we actually have
  664. * our choice of what cipher to use. */
  665. const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
  666. /* This list is autogenerated with the gen_server_ciphers.py script;
  667. * don't hand-edit it. */
  668. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  669. TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
  670. #endif
  671. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  672. TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
  673. #endif
  674. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
  675. TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
  676. #endif
  677. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
  678. TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
  679. #endif
  680. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
  681. TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
  682. #endif
  683. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
  684. TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
  685. #endif
  686. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
  687. TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
  688. #endif
  689. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
  690. TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
  691. #endif
  692. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
  693. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
  694. #endif
  695. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
  696. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
  697. #endif
  698. /* Required */
  699. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
  700. /* Required */
  701. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
  702. #ifdef TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA
  703. TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":"
  704. #endif
  705. /* Required */
  706. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA;
  707. /* Note: to set up your own private testing network with link crypto
  708. * disabled, set your Tors' cipher list to
  709. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  710. * with any of the "real" Tors, though. */
  711. #ifdef V2_HANDSHAKE_CLIENT
  712. #define CIPHER(id, name) name ":"
  713. #define XCIPHER(id, name)
  714. /** List of ciphers that clients should advertise, omitting items that
  715. * our OpenSSL doesn't know about. */
  716. static const char CLIENT_CIPHER_LIST[] =
  717. #include "./ciphers.inc"
  718. /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
  719. * of any cipher we say. */
  720. "!SSLv2"
  721. ;
  722. #undef CIPHER
  723. #undef XCIPHER
  724. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  725. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  726. /** A list of all the ciphers that clients should advertise, including items
  727. * that OpenSSL might not know about. */
  728. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  729. #define CIPHER(id, name) { id, name },
  730. #define XCIPHER(id, name) { id, #name },
  731. #include "./ciphers.inc"
  732. #undef CIPHER
  733. #undef XCIPHER
  734. };
  735. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  736. static const int N_CLIENT_CIPHERS = ARRAY_LENGTH(CLIENT_CIPHER_INFO_LIST);
  737. #endif
  738. #ifndef V2_HANDSHAKE_CLIENT
  739. #undef CLIENT_CIPHER_LIST
  740. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  741. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  742. #endif
  743. /** Free all storage held in <b>cert</b> */
  744. void
  745. tor_x509_cert_free(tor_x509_cert_t *cert)
  746. {
  747. if (! cert)
  748. return;
  749. if (cert->cert)
  750. X509_free(cert->cert);
  751. tor_free(cert->encoded);
  752. memwipe(cert, 0x03, sizeof(*cert));
  753. tor_free(cert);
  754. }
  755. /**
  756. * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
  757. *
  758. * Steals a reference to x509_cert.
  759. */
  760. static tor_x509_cert_t *
  761. tor_x509_cert_new(X509 *x509_cert)
  762. {
  763. tor_x509_cert_t *cert;
  764. EVP_PKEY *pkey;
  765. RSA *rsa;
  766. int length;
  767. unsigned char *buf = NULL;
  768. if (!x509_cert)
  769. return NULL;
  770. length = i2d_X509(x509_cert, &buf);
  771. cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
  772. if (length <= 0 || buf == NULL) {
  773. tor_free(cert);
  774. log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
  775. X509_free(x509_cert);
  776. return NULL;
  777. }
  778. cert->encoded_len = (size_t) length;
  779. cert->encoded = tor_malloc(length);
  780. memcpy(cert->encoded, buf, length);
  781. OPENSSL_free(buf);
  782. cert->cert = x509_cert;
  783. crypto_digest_all(&cert->cert_digests,
  784. (char*)cert->encoded, cert->encoded_len);
  785. if ((pkey = X509_get_pubkey(x509_cert)) &&
  786. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  787. crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
  788. crypto_pk_get_all_digests(pk, &cert->pkey_digests);
  789. cert->pkey_digests_set = 1;
  790. crypto_pk_free(pk);
  791. EVP_PKEY_free(pkey);
  792. }
  793. return cert;
  794. }
  795. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  796. * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
  797. * success and NULL on failure. */
  798. tor_x509_cert_t *
  799. tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
  800. {
  801. X509 *x509;
  802. const unsigned char *cp = (const unsigned char *)certificate;
  803. tor_x509_cert_t *newcert;
  804. tor_assert(certificate);
  805. check_no_tls_errors();
  806. if (certificate_len > INT_MAX)
  807. goto err;
  808. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  809. if (!x509)
  810. goto err; /* Couldn't decode */
  811. if (cp - certificate != (int)certificate_len) {
  812. X509_free(x509);
  813. goto err; /* Didn't use all the bytes */
  814. }
  815. newcert = tor_x509_cert_new(x509);
  816. if (!newcert) {
  817. goto err;
  818. }
  819. if (newcert->encoded_len != certificate_len ||
  820. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  821. /* Cert wasn't in DER */
  822. tor_x509_cert_free(newcert);
  823. goto err;
  824. }
  825. return newcert;
  826. err:
  827. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
  828. return NULL;
  829. }
  830. /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
  831. * representation and length, respectively. */
  832. void
  833. tor_x509_cert_get_der(const tor_x509_cert_t *cert,
  834. const uint8_t **encoded_out, size_t *size_out)
  835. {
  836. tor_assert(cert);
  837. tor_assert(encoded_out);
  838. tor_assert(size_out);
  839. *encoded_out = cert->encoded;
  840. *size_out = cert->encoded_len;
  841. }
  842. /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
  843. * cert's public key is not one we know how to take the digest of. */
  844. const digests_t *
  845. tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
  846. {
  847. if (cert->pkey_digests_set)
  848. return &cert->pkey_digests;
  849. else
  850. return NULL;
  851. }
  852. /** Return a set of digests for the public key in <b>cert</b>. */
  853. const digests_t *
  854. tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
  855. {
  856. return &cert->cert_digests;
  857. }
  858. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  859. * references. */
  860. static void
  861. tor_tls_context_decref(tor_tls_context_t *ctx)
  862. {
  863. tor_assert(ctx);
  864. if (--ctx->refcnt == 0) {
  865. SSL_CTX_free(ctx->ctx);
  866. tor_x509_cert_free(ctx->my_link_cert);
  867. tor_x509_cert_free(ctx->my_id_cert);
  868. tor_x509_cert_free(ctx->my_auth_cert);
  869. crypto_pk_free(ctx->link_key);
  870. crypto_pk_free(ctx->auth_key);
  871. tor_free(ctx);
  872. }
  873. }
  874. /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
  875. * and ID certificate that we're currently using for our V3 in-protocol
  876. * handshake's certificate chain. If <b>server</b> is true, provide the certs
  877. * that we use in server mode; otherwise, provide the certs that we use in
  878. * client mode. */
  879. int
  880. tor_tls_get_my_certs(int server,
  881. const tor_x509_cert_t **link_cert_out,
  882. const tor_x509_cert_t **id_cert_out)
  883. {
  884. tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
  885. if (! ctx)
  886. return -1;
  887. if (link_cert_out)
  888. *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
  889. if (id_cert_out)
  890. *id_cert_out = ctx->my_id_cert;
  891. return 0;
  892. }
  893. /**
  894. * Return the authentication key that we use to authenticate ourselves as a
  895. * client in the V3 in-protocol handshake.
  896. */
  897. crypto_pk_t *
  898. tor_tls_get_my_client_auth_key(void)
  899. {
  900. if (! client_tls_context)
  901. return NULL;
  902. return client_tls_context->auth_key;
  903. }
  904. /**
  905. * Return a newly allocated copy of the public key that a certificate
  906. * certifies. Return NULL if the cert's key is not RSA.
  907. */
  908. crypto_pk_t *
  909. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  910. {
  911. crypto_pk_t *result = NULL;
  912. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  913. RSA *rsa;
  914. if (!pkey)
  915. return NULL;
  916. rsa = EVP_PKEY_get1_RSA(pkey);
  917. if (!rsa) {
  918. EVP_PKEY_free(pkey);
  919. return NULL;
  920. }
  921. result = crypto_new_pk_from_rsa_(rsa);
  922. EVP_PKEY_free(pkey);
  923. return result;
  924. }
  925. /** Return true iff the other side of <b>tls</b> has authenticated to us, and
  926. * the key certified in <b>cert</b> is the same as the key they used to do it.
  927. */
  928. int
  929. tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert)
  930. {
  931. X509 *peercert = SSL_get_peer_certificate(tls->ssl);
  932. EVP_PKEY *link_key = NULL, *cert_key = NULL;
  933. int result;
  934. if (!peercert)
  935. return 0;
  936. link_key = X509_get_pubkey(peercert);
  937. cert_key = X509_get_pubkey(cert->cert);
  938. result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
  939. X509_free(peercert);
  940. if (link_key)
  941. EVP_PKEY_free(link_key);
  942. if (cert_key)
  943. EVP_PKEY_free(cert_key);
  944. return result;
  945. }
  946. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  947. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  948. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  949. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  950. * we couldn't check it. */
  951. int
  952. tor_tls_cert_is_valid(int severity,
  953. const tor_x509_cert_t *cert,
  954. const tor_x509_cert_t *signing_cert,
  955. int check_rsa_1024)
  956. {
  957. check_no_tls_errors();
  958. EVP_PKEY *cert_key;
  959. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  960. int r, key_ok = 0;
  961. if (!signing_key)
  962. goto bad;
  963. r = X509_verify(cert->cert, signing_key);
  964. EVP_PKEY_free(signing_key);
  965. if (r <= 0)
  966. goto bad;
  967. /* okay, the signature checked out right. Now let's check the check the
  968. * lifetime. */
  969. if (check_cert_lifetime_internal(severity, cert->cert,
  970. 48*60*60, 30*24*60*60) < 0)
  971. goto bad;
  972. cert_key = X509_get_pubkey(cert->cert);
  973. if (check_rsa_1024 && cert_key) {
  974. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  975. if (rsa && BN_num_bits(rsa->n) == 1024)
  976. key_ok = 1;
  977. if (rsa)
  978. RSA_free(rsa);
  979. } else if (cert_key) {
  980. int min_bits = 1024;
  981. #ifdef EVP_PKEY_EC
  982. if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
  983. min_bits = 128;
  984. #endif
  985. if (EVP_PKEY_bits(cert_key) >= min_bits)
  986. key_ok = 1;
  987. }
  988. EVP_PKEY_free(cert_key);
  989. if (!key_ok)
  990. goto bad;
  991. /* XXXX compare DNs or anything? */
  992. return 1;
  993. bad:
  994. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
  995. return 0;
  996. }
  997. /** Increase the reference count of <b>ctx</b>. */
  998. static void
  999. tor_tls_context_incref(tor_tls_context_t *ctx)
  1000. {
  1001. ++ctx->refcnt;
  1002. }
  1003. /** Create new global client and server TLS contexts.
  1004. *
  1005. * If <b>server_identity</b> is NULL, this will not generate a server
  1006. * TLS context. If TOR_TLS_CTX_IS_PUBLIC_SERVER is set in <b>flags</b>, use
  1007. * the same TLS context for incoming and outgoing connections, and
  1008. * ignore <b>client_identity</b>. If one of TOR_TLS_CTX_USE_ECDHE_P{224,256}
  1009. * is set in <b>flags</b>, use that ECDHE group if possible; otherwise use
  1010. * the default ECDHE group. */
  1011. int
  1012. tor_tls_context_init(unsigned flags,
  1013. crypto_pk_t *client_identity,
  1014. crypto_pk_t *server_identity,
  1015. unsigned int key_lifetime)
  1016. {
  1017. int rv1 = 0;
  1018. int rv2 = 0;
  1019. const int is_public_server = flags & TOR_TLS_CTX_IS_PUBLIC_SERVER;
  1020. check_no_tls_errors();
  1021. if (is_public_server) {
  1022. tor_tls_context_t *new_ctx;
  1023. tor_tls_context_t *old_ctx;
  1024. tor_assert(server_identity != NULL);
  1025. rv1 = tor_tls_context_init_one(&server_tls_context,
  1026. server_identity,
  1027. key_lifetime, flags, 0);
  1028. if (rv1 >= 0) {
  1029. new_ctx = server_tls_context;
  1030. tor_tls_context_incref(new_ctx);
  1031. old_ctx = client_tls_context;
  1032. client_tls_context = new_ctx;
  1033. if (old_ctx != NULL) {
  1034. tor_tls_context_decref(old_ctx);
  1035. }
  1036. }
  1037. } else {
  1038. if (server_identity != NULL) {
  1039. rv1 = tor_tls_context_init_one(&server_tls_context,
  1040. server_identity,
  1041. key_lifetime,
  1042. flags,
  1043. 0);
  1044. } else {
  1045. tor_tls_context_t *old_ctx = server_tls_context;
  1046. server_tls_context = NULL;
  1047. if (old_ctx != NULL) {
  1048. tor_tls_context_decref(old_ctx);
  1049. }
  1050. }
  1051. rv2 = tor_tls_context_init_one(&client_tls_context,
  1052. client_identity,
  1053. key_lifetime,
  1054. flags,
  1055. 1);
  1056. }
  1057. tls_log_errors(NULL, LOG_WARN, LD_CRYPTO, "constructing a TLS context");
  1058. return MIN(rv1, rv2);
  1059. }
  1060. /** Create a new global TLS context.
  1061. *
  1062. * You can call this function multiple times. Each time you call it,
  1063. * it generates new certificates; all new connections will use
  1064. * the new SSL context.
  1065. */
  1066. static int
  1067. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  1068. crypto_pk_t *identity,
  1069. unsigned int key_lifetime,
  1070. unsigned int flags,
  1071. int is_client)
  1072. {
  1073. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  1074. key_lifetime,
  1075. flags,
  1076. is_client);
  1077. tor_tls_context_t *old_ctx = *ppcontext;
  1078. if (new_ctx != NULL) {
  1079. *ppcontext = new_ctx;
  1080. /* Free the old context if one existed. */
  1081. if (old_ctx != NULL) {
  1082. /* This is safe even if there are open connections: we reference-
  1083. * count tor_tls_context_t objects. */
  1084. tor_tls_context_decref(old_ctx);
  1085. }
  1086. }
  1087. return ((new_ctx != NULL) ? 0 : -1);
  1088. }
  1089. /** The group we should use for ecdhe when none was selected. */
  1090. #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
  1091. /** Create a new TLS context for use with Tor TLS handshakes.
  1092. * <b>identity</b> should be set to the identity key used to sign the
  1093. * certificate.
  1094. */
  1095. static tor_tls_context_t *
  1096. tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
  1097. unsigned flags, int is_client)
  1098. {
  1099. crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
  1100. EVP_PKEY *pkey = NULL;
  1101. tor_tls_context_t *result = NULL;
  1102. X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
  1103. char *nickname = NULL, *nn2 = NULL;
  1104. tor_tls_init();
  1105. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  1106. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1107. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  1108. #else
  1109. nn2 = crypto_random_hostname(8, 20, "www.", ".com");
  1110. #endif
  1111. /* Generate short-term RSA key for use with TLS. */
  1112. if (!(rsa = crypto_pk_new()))
  1113. goto error;
  1114. if (crypto_pk_generate_key(rsa)<0)
  1115. goto error;
  1116. if (!is_client) {
  1117. /* Generate short-term RSA key for use in the in-protocol ("v3")
  1118. * authentication handshake. */
  1119. if (!(rsa_auth = crypto_pk_new()))
  1120. goto error;
  1121. if (crypto_pk_generate_key(rsa_auth)<0)
  1122. goto error;
  1123. /* Create a link certificate signed by identity key. */
  1124. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  1125. key_lifetime);
  1126. /* Create self-signed certificate for identity key. */
  1127. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  1128. IDENTITY_CERT_LIFETIME);
  1129. /* Create an authentication certificate signed by identity key. */
  1130. authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
  1131. key_lifetime);
  1132. if (!cert || !idcert || !authcert) {
  1133. log_warn(LD_CRYPTO, "Error creating certificate");
  1134. goto error;
  1135. }
  1136. }
  1137. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  1138. result->refcnt = 1;
  1139. if (!is_client) {
  1140. result->my_link_cert = tor_x509_cert_new(X509_dup(cert));
  1141. result->my_id_cert = tor_x509_cert_new(X509_dup(idcert));
  1142. result->my_auth_cert = tor_x509_cert_new(X509_dup(authcert));
  1143. if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
  1144. goto error;
  1145. result->link_key = crypto_pk_dup_key(rsa);
  1146. result->auth_key = crypto_pk_dup_key(rsa_auth);
  1147. }
  1148. #if 0
  1149. /* Tell OpenSSL to only use TLS1. This may have subtly different results
  1150. * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
  1151. * investigation before we consider adjusting it. It should be compatible
  1152. * with existing Tors. */
  1153. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  1154. goto error;
  1155. #endif
  1156. /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
  1157. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  1158. goto error;
  1159. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  1160. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
  1161. /* Prefer the server's ordering of ciphers: the client's ordering has
  1162. * historically been chosen for fingerprinting resistance. */
  1163. SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  1164. /* Disable TLS1.1 and TLS1.2 if they exist. We need to do this to
  1165. * workaround a bug present in all OpenSSL 1.0.1 versions (as of 1
  1166. * June 2012), wherein renegotiating while using one of these TLS
  1167. * protocols will cause the client to send a TLS 1.0 ServerHello
  1168. * rather than a ServerHello written with the appropriate protocol
  1169. * version. Once some version of OpenSSL does TLS1.1 and TLS1.2
  1170. * renegotiation properly, we can turn them back on when built with
  1171. * that version. */
  1172. #if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,1,'e')
  1173. #ifdef SSL_OP_NO_TLSv1_2
  1174. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_2);
  1175. #endif
  1176. #ifdef SSL_OP_NO_TLSv1_1
  1177. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_1);
  1178. #endif
  1179. #endif
  1180. /* Disable TLS tickets if they're supported. We never want to use them;
  1181. * using them can make our perfect forward secrecy a little worse, *and*
  1182. * create an opportunity to fingerprint us (since it's unusual to use them
  1183. * with TLS sessions turned off).
  1184. *
  1185. * In 0.2.4, clients advertise support for them though, to avoid a TLS
  1186. * distinguishability vector. This can give us worse PFS, though, if we
  1187. * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
  1188. * be few such servers by the time 0.2.4 is more stable.
  1189. */
  1190. #ifdef SSL_OP_NO_TICKET
  1191. if (! is_client) {
  1192. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
  1193. }
  1194. #endif
  1195. /* XXX This block is now obsolete. */
  1196. if (
  1197. #ifdef DISABLE_SSL3_HANDSHAKE
  1198. 1 ||
  1199. #endif
  1200. SSLeay() < OPENSSL_V(0,9,8,'s') ||
  1201. (SSLeay() >= OPENSSL_V_SERIES(0,9,9) &&
  1202. SSLeay() < OPENSSL_V(1,0,0,'f'))) {
  1203. /* And not SSL3 if it's subject to CVE-2011-4576. */
  1204. log_info(LD_NET, "Disabling SSLv3 because this OpenSSL version "
  1205. "might otherwise be vulnerable to CVE-2011-4576 "
  1206. "(compile-time version %08lx (%s); "
  1207. "runtime version %08lx (%s))",
  1208. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  1209. (unsigned long)SSLeay(), SSLeay_version(SSLEAY_VERSION));
  1210. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
  1211. }
  1212. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  1213. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
  1214. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  1215. SSL_CTX_set_options(result->ctx,
  1216. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1217. #endif
  1218. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1219. * as authenticating any earlier-received data.
  1220. */
  1221. if (use_unsafe_renegotiation_op) {
  1222. SSL_CTX_set_options(result->ctx,
  1223. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1224. }
  1225. #ifndef OPENSSL_NO_COMP
  1226. /* Don't actually allow compression; it uses ram and time, but the data
  1227. * we transmit is all encrypted anyway. */
  1228. if (result->ctx->comp_methods)
  1229. result->ctx->comp_methods = NULL;
  1230. #endif
  1231. #ifdef SSL_MODE_RELEASE_BUFFERS
  1232. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  1233. #endif
  1234. if (! is_client) {
  1235. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  1236. goto error;
  1237. X509_free(cert); /* We just added a reference to cert. */
  1238. cert=NULL;
  1239. if (idcert) {
  1240. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  1241. tor_assert(s);
  1242. X509_STORE_add_cert(s, idcert);
  1243. X509_free(idcert); /* The context now owns the reference to idcert */
  1244. idcert = NULL;
  1245. }
  1246. }
  1247. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  1248. if (!is_client) {
  1249. tor_assert(rsa);
  1250. if (!(pkey = crypto_pk_get_evp_pkey_(rsa,1)))
  1251. goto error;
  1252. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  1253. goto error;
  1254. EVP_PKEY_free(pkey);
  1255. pkey = NULL;
  1256. if (!SSL_CTX_check_private_key(result->ctx))
  1257. goto error;
  1258. }
  1259. {
  1260. crypto_dh_t *dh = crypto_dh_new(DH_TYPE_TLS);
  1261. tor_assert(dh);
  1262. SSL_CTX_set_tmp_dh(result->ctx, crypto_dh_get_dh_(dh));
  1263. crypto_dh_free(dh);
  1264. }
  1265. #if (!defined(OPENSSL_NO_EC) && \
  1266. OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0))
  1267. if (! is_client) {
  1268. int nid;
  1269. EC_KEY *ec_key;
  1270. if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
  1271. nid = NID_secp224r1;
  1272. else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
  1273. nid = NID_X9_62_prime256v1;
  1274. else
  1275. nid = NID_tor_default_ecdhe_group;
  1276. /* Use P-256 for ECDHE. */
  1277. ec_key = EC_KEY_new_by_curve_name(nid);
  1278. if (ec_key != NULL) /*XXXX Handle errors? */
  1279. SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
  1280. EC_KEY_free(ec_key);
  1281. }
  1282. #else
  1283. (void)flags;
  1284. #endif
  1285. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  1286. always_accept_verify_cb);
  1287. /* let us realloc bufs that we're writing from */
  1288. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  1289. if (rsa)
  1290. crypto_pk_free(rsa);
  1291. if (rsa_auth)
  1292. crypto_pk_free(rsa_auth);
  1293. X509_free(authcert);
  1294. tor_free(nickname);
  1295. tor_free(nn2);
  1296. return result;
  1297. error:
  1298. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  1299. tor_free(nickname);
  1300. tor_free(nn2);
  1301. if (pkey)
  1302. EVP_PKEY_free(pkey);
  1303. if (rsa)
  1304. crypto_pk_free(rsa);
  1305. if (rsa_auth)
  1306. crypto_pk_free(rsa_auth);
  1307. if (result)
  1308. tor_tls_context_decref(result);
  1309. if (cert)
  1310. X509_free(cert);
  1311. if (idcert)
  1312. X509_free(idcert);
  1313. if (authcert)
  1314. X509_free(authcert);
  1315. return NULL;
  1316. }
  1317. /** Invoked when a TLS state changes: log the change at severity 'debug' */
  1318. static void
  1319. tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
  1320. {
  1321. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  1322. ssl, SSL_state_string_long(ssl), type, val);
  1323. }
  1324. /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
  1325. const char *
  1326. tor_tls_get_ciphersuite_name(tor_tls_t *tls)
  1327. {
  1328. return SSL_get_cipher(tls->ssl);
  1329. }
  1330. #ifdef V2_HANDSHAKE_SERVER
  1331. /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
  1332. * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
  1333. * that it claims to support. We'll prune this list to remove the ciphers
  1334. * *we* don't recognize. */
  1335. static uint16_t v2_cipher_list[] = {
  1336. 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
  1337. 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
  1338. 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
  1339. 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
  1340. 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
  1341. 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
  1342. 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
  1343. 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
  1344. 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
  1345. 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
  1346. 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
  1347. 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
  1348. 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
  1349. 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
  1350. 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
  1351. 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
  1352. 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
  1353. 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
  1354. 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
  1355. 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
  1356. 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
  1357. 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
  1358. 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
  1359. 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
  1360. 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
  1361. 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
  1362. 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
  1363. 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
  1364. 0
  1365. };
  1366. /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
  1367. static int v2_cipher_list_pruned = 0;
  1368. /** Return 0 if <b>m</b> does not support the cipher with ID <b>cipher</b>;
  1369. * return 1 if it does support it, or if we have no way to tell. */
  1370. static int
  1371. find_cipher_by_id(const SSL_METHOD *m, uint16_t cipher)
  1372. {
  1373. const SSL_CIPHER *c;
  1374. #ifdef HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR
  1375. if (m && m->get_cipher_by_char) {
  1376. unsigned char cipherid[3];
  1377. set_uint16(cipherid, htons(cipher));
  1378. cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
  1379. * with a two-byte 'cipherid', it may look for a v2
  1380. * cipher with the appropriate 3 bytes. */
  1381. c = m->get_cipher_by_char(cipherid);
  1382. if (c)
  1383. tor_assert((c->id & 0xffff) == cipher);
  1384. return c != NULL;
  1385. } else
  1386. #endif
  1387. if (m && m->get_cipher && m->num_ciphers) {
  1388. /* It would seem that some of the "let's-clean-up-openssl" forks have
  1389. * removed the get_cipher_by_char function. Okay, so now you get a
  1390. * quadratic search.
  1391. */
  1392. int i;
  1393. for (i = 0; i < m->num_ciphers(); ++i) {
  1394. c = m->get_cipher(i);
  1395. if (c && (c->id & 0xffff) == cipher) {
  1396. return 1;
  1397. }
  1398. }
  1399. return 0;
  1400. } else {
  1401. return 1; /* No way to search */
  1402. }
  1403. }
  1404. /** Remove from v2_cipher_list every cipher that we don't support, so that
  1405. * comparing v2_cipher_list to a client's cipher list will give a sensible
  1406. * result. */
  1407. static void
  1408. prune_v2_cipher_list(void)
  1409. {
  1410. uint16_t *inp, *outp;
  1411. const SSL_METHOD *m = SSLv23_method();
  1412. inp = outp = v2_cipher_list;
  1413. while (*inp) {
  1414. if (find_cipher_by_id(m, *inp)) {
  1415. *outp++ = *inp++;
  1416. } else {
  1417. inp++;
  1418. }
  1419. }
  1420. *outp = 0;
  1421. v2_cipher_list_pruned = 1;
  1422. }
  1423. /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
  1424. * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
  1425. * CIPHERS_UNRESTRICTED.
  1426. **/
  1427. static int
  1428. tor_tls_classify_client_ciphers(const SSL *ssl,
  1429. STACK_OF(SSL_CIPHER) *peer_ciphers)
  1430. {
  1431. int i, res;
  1432. tor_tls_t *tor_tls;
  1433. if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
  1434. prune_v2_cipher_list();
  1435. tor_tls = tor_tls_get_by_ssl(ssl);
  1436. if (tor_tls && tor_tls->client_cipher_list_type)
  1437. return tor_tls->client_cipher_list_type;
  1438. /* If we reached this point, we just got a client hello. See if there is
  1439. * a cipher list. */
  1440. if (!peer_ciphers) {
  1441. log_info(LD_NET, "No ciphers on session");
  1442. res = CIPHERS_ERR;
  1443. goto done;
  1444. }
  1445. /* Now we need to see if there are any ciphers whose presence means we're
  1446. * dealing with an updated Tor. */
  1447. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  1448. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  1449. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1450. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  1451. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  1452. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  1453. strcmp(ciphername, "(NONE)")) {
  1454. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  1455. // return 1;
  1456. goto v2_or_higher;
  1457. }
  1458. }
  1459. res = CIPHERS_V1;
  1460. goto done;
  1461. v2_or_higher:
  1462. {
  1463. const uint16_t *v2_cipher = v2_cipher_list;
  1464. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  1465. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  1466. uint16_t id = cipher->id & 0xffff;
  1467. if (id == 0x00ff) /* extended renegotiation indicator. */
  1468. continue;
  1469. if (!id || id != *v2_cipher) {
  1470. res = CIPHERS_UNRESTRICTED;
  1471. goto dump_ciphers;
  1472. }
  1473. ++v2_cipher;
  1474. }
  1475. if (*v2_cipher != 0) {
  1476. res = CIPHERS_UNRESTRICTED;
  1477. goto dump_ciphers;
  1478. }
  1479. res = CIPHERS_V2;
  1480. }
  1481. dump_ciphers:
  1482. {
  1483. smartlist_t *elts = smartlist_new();
  1484. char *s;
  1485. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  1486. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  1487. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1488. smartlist_add(elts, (char*)ciphername);
  1489. }
  1490. s = smartlist_join_strings(elts, ":", 0, NULL);
  1491. log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
  1492. (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
  1493. tor_free(s);
  1494. smartlist_free(elts);
  1495. }
  1496. done:
  1497. if (tor_tls)
  1498. return tor_tls->client_cipher_list_type = res;
  1499. return res;
  1500. }
  1501. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  1502. * a list that indicates that the client knows how to do the v2 TLS connection
  1503. * handshake. */
  1504. static int
  1505. tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
  1506. {
  1507. SSL_SESSION *session;
  1508. if (!(session = SSL_get_session((SSL *)ssl))) {
  1509. log_info(LD_NET, "No session on TLS?");
  1510. return CIPHERS_ERR;
  1511. }
  1512. return tor_tls_classify_client_ciphers(ssl, session->ciphers) >= CIPHERS_V2;
  1513. }
  1514. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  1515. * changes state. We use this:
  1516. * <ul><li>To alter the state of the handshake partway through, so we
  1517. * do not send or request extra certificates in v2 handshakes.</li>
  1518. * <li>To detect renegotiation</li></ul>
  1519. */
  1520. static void
  1521. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  1522. {
  1523. tor_tls_t *tls;
  1524. (void) val;
  1525. tor_tls_debug_state_callback(ssl, type, val);
  1526. if (type != SSL_CB_ACCEPT_LOOP)
  1527. return;
  1528. if ((ssl->state != SSL3_ST_SW_SRVR_HELLO_A) &&
  1529. (ssl->state != SSL3_ST_SW_SRVR_HELLO_B))
  1530. return;
  1531. tls = tor_tls_get_by_ssl(ssl);
  1532. if (tls) {
  1533. /* Check whether we're watching for renegotiates. If so, this is one! */
  1534. if (tls->negotiated_callback)
  1535. tls->got_renegotiate = 1;
  1536. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  1537. ++tls->server_handshake_count;
  1538. } else {
  1539. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1540. return;
  1541. }
  1542. /* Now check the cipher list. */
  1543. if (tor_tls_client_is_using_v2_ciphers(ssl)) {
  1544. if (tls->wasV2Handshake)
  1545. return; /* We already turned this stuff off for the first handshake;
  1546. * This is a renegotiation. */
  1547. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  1548. * Let's hope openssl doesn't notice! */
  1549. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  1550. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  1551. /* Don't send a hello request. */
  1552. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  1553. if (tls) {
  1554. tls->wasV2Handshake = 1;
  1555. #ifdef USE_BUFFEREVENTS
  1556. if (use_unsafe_renegotiation_flag)
  1557. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1558. #endif
  1559. } else {
  1560. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1561. }
  1562. }
  1563. }
  1564. #endif
  1565. #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
  1566. /** Callback to get invoked on a server after we've read the list of ciphers
  1567. * the client supports, but before we pick our own ciphersuite.
  1568. *
  1569. * We can't abuse an info_cb for this, since by the time one of the
  1570. * client_hello info_cbs is called, we've already picked which ciphersuite to
  1571. * use.
  1572. *
  1573. * Technically, this function is an abuse of this callback, since the point of
  1574. * a session_secret_cb is to try to set up and/or verify a shared-secret for
  1575. * authentication on the fly. But as long as we return 0, we won't actually be
  1576. * setting up a shared secret, and all will be fine.
  1577. */
  1578. static int
  1579. tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
  1580. STACK_OF(SSL_CIPHER) *peer_ciphers,
  1581. SSL_CIPHER **cipher, void *arg)
  1582. {
  1583. (void) secret;
  1584. (void) secret_len;
  1585. (void) peer_ciphers;
  1586. (void) cipher;
  1587. (void) arg;
  1588. if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
  1589. CIPHERS_UNRESTRICTED) {
  1590. SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
  1591. }
  1592. SSL_set_session_secret_cb(ssl, NULL, NULL);
  1593. return 0;
  1594. }
  1595. static void
  1596. tor_tls_setup_session_secret_cb(tor_tls_t *tls)
  1597. {
  1598. SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
  1599. }
  1600. #else
  1601. #define tor_tls_setup_session_secret_cb(tls) STMT_NIL
  1602. #endif
  1603. /** Explain which ciphers we're missing. */
  1604. static void
  1605. log_unsupported_ciphers(smartlist_t *unsupported)
  1606. {
  1607. char *joined;
  1608. log_notice(LD_NET, "We weren't able to find support for all of the "
  1609. "TLS ciphersuites that we wanted to advertise. This won't "
  1610. "hurt security, but it might make your Tor (if run as a client) "
  1611. "more easy for censors to block.");
  1612. if (SSLeay() < 0x10000000L) {
  1613. log_notice(LD_NET, "To correct this, use a more recent OpenSSL, "
  1614. "built without disabling any secure ciphers or features.");
  1615. } else {
  1616. log_notice(LD_NET, "To correct this, use a version of OpenSSL "
  1617. "built with none of its ciphers disabled.");
  1618. }
  1619. joined = smartlist_join_strings(unsupported, ":", 0, NULL);
  1620. log_info(LD_NET, "The unsupported ciphers were: %s", joined);
  1621. tor_free(joined);
  1622. }
  1623. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  1624. * a list designed to mimic a common web browser. We might not be able to do
  1625. * that if OpenSSL doesn't support all the ciphers we want. Some of the
  1626. * ciphers in the list won't actually be implemented by OpenSSL: that's okay
  1627. * so long as the server doesn't select them.
  1628. *
  1629. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  1630. * anything; we'll just fail later when we try to look up the cipher in
  1631. * ssl->cipher_list_by_id.]
  1632. */
  1633. static void
  1634. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  1635. {
  1636. #ifdef V2_HANDSHAKE_CLIENT
  1637. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  1638. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  1639. * we want to use/advertise. */
  1640. int i = 0, j = 0;
  1641. smartlist_t *unsupported = smartlist_new();
  1642. /* First, create a dummy SSL_CIPHER for every cipher. */
  1643. CLIENT_CIPHER_DUMMIES =
  1644. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  1645. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  1646. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  1647. /* The "3<<24" here signifies that the cipher is supposed to work with
  1648. * SSL3 and TLS1. */
  1649. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  1650. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  1651. }
  1652. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  1653. tor_assert(CLIENT_CIPHER_STACK);
  1654. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  1655. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  1656. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1657. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  1658. }
  1659. /* Then copy as many ciphers as we can from the good list, inserting
  1660. * dummies as needed. Let j be an index into list of ciphers we have
  1661. * (*ciphers) and let i be an index into the ciphers we want
  1662. * (CLIENT_INFO_CIPHER_LIST). We are building a list of ciphers in
  1663. * CLIENT_CIPHER_STACK.
  1664. */
  1665. for (i = j = 0; i < N_CLIENT_CIPHERS; ) {
  1666. SSL_CIPHER *cipher = NULL;
  1667. if (j < sk_SSL_CIPHER_num(*ciphers))
  1668. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1669. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  1670. /* Skip over non-v3 ciphers entirely. (This should no longer be
  1671. * needed, thanks to saying !SSLv2 above.) */
  1672. log_debug(LD_NET, "Skipping v%d cipher %s",
  1673. (int)((cipher->id>>24) & 0xff),
  1674. cipher->name);
  1675. ++j;
  1676. } else if (cipher &&
  1677. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  1678. /* "cipher" is the cipher we expect. Put it on the list. */
  1679. log_debug(LD_NET, "Found cipher %s", cipher->name);
  1680. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  1681. ++j;
  1682. ++i;
  1683. } else if (!strcmp(CLIENT_CIPHER_DUMMIES[i].name,
  1684. "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA")) {
  1685. /* We found bogus cipher 0xfeff, which OpenSSL doesn't support and
  1686. * never has. For this one, we need a dummy. */
  1687. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  1688. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  1689. ++i;
  1690. } else {
  1691. /* OpenSSL doesn't have this one. */
  1692. log_debug(LD_NET, "Completely omitting unsupported cipher %s",
  1693. CLIENT_CIPHER_INFO_LIST[i].name);
  1694. smartlist_add(unsupported, (char*) CLIENT_CIPHER_INFO_LIST[i].name);
  1695. ++i;
  1696. }
  1697. }
  1698. if (smartlist_len(unsupported))
  1699. log_unsupported_ciphers(unsupported);
  1700. smartlist_free(unsupported);
  1701. }
  1702. sk_SSL_CIPHER_free(*ciphers);
  1703. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  1704. tor_assert(*ciphers);
  1705. #else
  1706. (void)ciphers;
  1707. #endif
  1708. }
  1709. /** Create a new TLS object from a file descriptor, and a flag to
  1710. * determine whether it is functioning as a server.
  1711. */
  1712. tor_tls_t *
  1713. tor_tls_new(int sock, int isServer)
  1714. {
  1715. BIO *bio = NULL;
  1716. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  1717. tor_tls_context_t *context = isServer ? server_tls_context :
  1718. client_tls_context;
  1719. result->magic = TOR_TLS_MAGIC;
  1720. check_no_tls_errors();
  1721. tor_assert(context); /* make sure somebody made it first */
  1722. if (!(result->ssl = SSL_new(context->ctx))) {
  1723. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  1724. tor_free(result);
  1725. goto err;
  1726. }
  1727. #ifdef SSL_set_tlsext_host_name
  1728. /* Browsers use the TLS hostname extension, so we should too. */
  1729. if (!isServer) {
  1730. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1731. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1732. tor_free(fake_hostname);
  1733. }
  1734. #endif
  1735. if (!SSL_set_cipher_list(result->ssl,
  1736. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1737. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1738. #ifdef SSL_set_tlsext_host_name
  1739. SSL_set_tlsext_host_name(result->ssl, NULL);
  1740. #endif
  1741. SSL_free(result->ssl);
  1742. tor_free(result);
  1743. goto err;
  1744. }
  1745. if (!isServer)
  1746. rectify_client_ciphers(&result->ssl->cipher_list);
  1747. result->socket = sock;
  1748. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1749. if (! bio) {
  1750. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1751. #ifdef SSL_set_tlsext_host_name
  1752. SSL_set_tlsext_host_name(result->ssl, NULL);
  1753. #endif
  1754. SSL_free(result->ssl);
  1755. tor_free(result);
  1756. goto err;
  1757. }
  1758. {
  1759. int set_worked =
  1760. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1761. if (!set_worked) {
  1762. log_warn(LD_BUG,
  1763. "Couldn't set the tls for an SSL*; connection will fail");
  1764. }
  1765. }
  1766. SSL_set_bio(result->ssl, bio, bio);
  1767. tor_tls_context_incref(context);
  1768. result->context = context;
  1769. result->state = TOR_TLS_ST_HANDSHAKE;
  1770. result->isServer = isServer;
  1771. result->wantwrite_n = 0;
  1772. result->last_write_count = BIO_number_written(bio);
  1773. result->last_read_count = BIO_number_read(bio);
  1774. if (result->last_write_count || result->last_read_count) {
  1775. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1776. result->last_read_count, result->last_write_count);
  1777. }
  1778. #ifdef V2_HANDSHAKE_SERVER
  1779. if (isServer) {
  1780. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  1781. } else
  1782. #endif
  1783. {
  1784. SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
  1785. }
  1786. if (isServer)
  1787. tor_tls_setup_session_secret_cb(result);
  1788. goto done;
  1789. err:
  1790. result = NULL;
  1791. done:
  1792. /* Not expected to get called. */
  1793. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1794. return result;
  1795. }
  1796. /** Make future log messages about <b>tls</b> display the address
  1797. * <b>address</b>.
  1798. */
  1799. void
  1800. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1801. {
  1802. tor_assert(tls);
  1803. tor_free(tls->address);
  1804. tls->address = tor_strdup(address);
  1805. }
  1806. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  1807. * next gets a client-side renegotiate in the middle of a read. Do not
  1808. * invoke this function until <em>after</em> initial handshaking is done!
  1809. */
  1810. void
  1811. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  1812. void (*cb)(tor_tls_t *, void *arg),
  1813. void *arg)
  1814. {
  1815. tls->negotiated_callback = cb;
  1816. tls->callback_arg = arg;
  1817. tls->got_renegotiate = 0;
  1818. #ifdef V2_HANDSHAKE_SERVER
  1819. if (cb) {
  1820. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  1821. } else {
  1822. SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
  1823. }
  1824. #endif
  1825. }
  1826. /** If this version of openssl requires it, turn on renegotiation on
  1827. * <b>tls</b>.
  1828. */
  1829. void
  1830. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1831. {
  1832. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1833. * as authenticating any earlier-received data. */
  1834. if (use_unsafe_renegotiation_flag) {
  1835. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1836. }
  1837. if (use_unsafe_renegotiation_op) {
  1838. SSL_set_options(tls->ssl,
  1839. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1840. }
  1841. }
  1842. /** If this version of openssl supports it, turn off renegotiation on
  1843. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  1844. * to use belt-and-suspenders here.)
  1845. */
  1846. void
  1847. tor_tls_block_renegotiation(tor_tls_t *tls)
  1848. {
  1849. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1850. }
  1851. /** Assert that the flags that allow legacy renegotiation are still set */
  1852. void
  1853. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1854. {
  1855. if (use_unsafe_renegotiation_flag) {
  1856. tor_assert(0 != (tls->ssl->s3->flags &
  1857. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1858. }
  1859. if (use_unsafe_renegotiation_op) {
  1860. long options = SSL_get_options(tls->ssl);
  1861. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1862. }
  1863. }
  1864. /** Return whether this tls initiated the connect (client) or
  1865. * received it (server). */
  1866. int
  1867. tor_tls_is_server(tor_tls_t *tls)
  1868. {
  1869. tor_assert(tls);
  1870. return tls->isServer;
  1871. }
  1872. /** Release resources associated with a TLS object. Does not close the
  1873. * underlying file descriptor.
  1874. */
  1875. void
  1876. tor_tls_free(tor_tls_t *tls)
  1877. {
  1878. if (!tls)
  1879. return;
  1880. tor_assert(tls->ssl);
  1881. {
  1882. size_t r,w;
  1883. tor_tls_get_n_raw_bytes(tls,&r,&w); /* ensure written_by_tls is updated */
  1884. }
  1885. #ifdef SSL_set_tlsext_host_name
  1886. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1887. #endif
  1888. SSL_free(tls->ssl);
  1889. tls->ssl = NULL;
  1890. tls->negotiated_callback = NULL;
  1891. if (tls->context)
  1892. tor_tls_context_decref(tls->context);
  1893. tor_free(tls->address);
  1894. tls->magic = 0x99999999;
  1895. tor_free(tls);
  1896. }
  1897. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1898. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1899. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1900. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1901. */
  1902. int
  1903. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1904. {
  1905. int r, err;
  1906. tor_assert(tls);
  1907. tor_assert(tls->ssl);
  1908. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1909. tor_assert(len<INT_MAX);
  1910. r = SSL_read(tls->ssl, cp, (int)len);
  1911. if (r > 0) {
  1912. #ifdef V2_HANDSHAKE_SERVER
  1913. if (tls->got_renegotiate) {
  1914. /* Renegotiation happened! */
  1915. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1916. if (tls->negotiated_callback)
  1917. tls->negotiated_callback(tls, tls->callback_arg);
  1918. tls->got_renegotiate = 0;
  1919. }
  1920. #endif
  1921. return r;
  1922. }
  1923. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1924. if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
  1925. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1926. tls->state = TOR_TLS_ST_CLOSED;
  1927. return TOR_TLS_CLOSE;
  1928. } else {
  1929. tor_assert(err != TOR_TLS_DONE);
  1930. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1931. return err;
  1932. }
  1933. }
  1934. /** Total number of bytes that we've used TLS to send. Used to track TLS
  1935. * overhead. */
  1936. static uint64_t total_bytes_written_over_tls = 0;
  1937. /** Total number of bytes that TLS has put on the network for us. Used to
  1938. * track TLS overhead. */
  1939. static uint64_t total_bytes_written_by_tls = 0;
  1940. /** Underlying function for TLS writing. Write up to <b>n</b>
  1941. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1942. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1943. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1944. */
  1945. int
  1946. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1947. {
  1948. int r, err;
  1949. tor_assert(tls);
  1950. tor_assert(tls->ssl);
  1951. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1952. tor_assert(n < INT_MAX);
  1953. if (n == 0)
  1954. return 0;
  1955. if (tls->wantwrite_n) {
  1956. /* if WANTWRITE last time, we must use the _same_ n as before */
  1957. tor_assert(n >= tls->wantwrite_n);
  1958. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1959. (int)n, (int)tls->wantwrite_n);
  1960. n = tls->wantwrite_n;
  1961. tls->wantwrite_n = 0;
  1962. }
  1963. r = SSL_write(tls->ssl, cp, (int)n);
  1964. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1965. if (err == TOR_TLS_DONE) {
  1966. total_bytes_written_over_tls += r;
  1967. return r;
  1968. }
  1969. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1970. tls->wantwrite_n = n;
  1971. }
  1972. return err;
  1973. }
  1974. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1975. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1976. * or TOR_TLS_WANTWRITE.
  1977. */
  1978. int
  1979. tor_tls_handshake(tor_tls_t *tls)
  1980. {
  1981. int r;
  1982. int oldstate;
  1983. tor_assert(tls);
  1984. tor_assert(tls->ssl);
  1985. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1986. check_no_tls_errors();
  1987. oldstate = tls->ssl->state;
  1988. if (tls->isServer) {
  1989. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1990. SSL_state_string_long(tls->ssl));
  1991. r = SSL_accept(tls->ssl);
  1992. } else {
  1993. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1994. SSL_state_string_long(tls->ssl));
  1995. r = SSL_connect(tls->ssl);
  1996. }
  1997. if (oldstate != tls->ssl->state)
  1998. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1999. tls, SSL_state_string_long(tls->ssl));
  2000. /* We need to call this here and not earlier, since OpenSSL has a penchant
  2001. * for clearing its flags when you say accept or connect. */
  2002. tor_tls_unblock_renegotiation(tls);
  2003. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  2004. if (ERR_peek_error() != 0) {
  2005. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  2006. "handshaking");
  2007. return TOR_TLS_ERROR_MISC;
  2008. }
  2009. if (r == TOR_TLS_DONE) {
  2010. tls->state = TOR_TLS_ST_OPEN;
  2011. return tor_tls_finish_handshake(tls);
  2012. }
  2013. return r;
  2014. }
  2015. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  2016. * should be called for the first handshake only: it determines whether the v1
  2017. * or the v2 handshake was used, and adjusts things for the renegotiation
  2018. * handshake as appropriate.
  2019. *
  2020. * tor_tls_handshake() calls this on its own; you only need to call this if
  2021. * bufferevent is doing the handshake for you.
  2022. */
  2023. int
  2024. tor_tls_finish_handshake(tor_tls_t *tls)
  2025. {
  2026. int r = TOR_TLS_DONE;
  2027. check_no_tls_errors();
  2028. if (tls->isServer) {
  2029. SSL_set_info_callback(tls->ssl, NULL);
  2030. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  2031. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  2032. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  2033. #ifdef V2_HANDSHAKE_SERVER
  2034. if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
  2035. /* This check is redundant, but back when we did it in the callback,
  2036. * we might have not been able to look up the tor_tls_t if the code
  2037. * was buggy. Fixing that. */
  2038. if (!tls->wasV2Handshake) {
  2039. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  2040. " get set. Fixing that.");
  2041. }
  2042. tls->wasV2Handshake = 1;
  2043. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  2044. " for renegotiation.");
  2045. } else {
  2046. tls->wasV2Handshake = 0;
  2047. }
  2048. #endif
  2049. } else {
  2050. #ifdef V2_HANDSHAKE_CLIENT
  2051. /* If we got no ID cert, we're a v2 handshake. */
  2052. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  2053. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  2054. int n_certs = sk_X509_num(chain);
  2055. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  2056. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  2057. "looks like a v1 handshake on %p", tls);
  2058. tls->wasV2Handshake = 0;
  2059. } else {
  2060. log_debug(LD_HANDSHAKE,
  2061. "Server sent back a single certificate; looks like "
  2062. "a v2 handshake on %p.", tls);
  2063. tls->wasV2Handshake = 1;
  2064. }
  2065. if (cert)
  2066. X509_free(cert);
  2067. #endif
  2068. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  2069. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  2070. r = TOR_TLS_ERROR_MISC;
  2071. }
  2072. }
  2073. tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
  2074. return r;
  2075. }
  2076. #ifdef USE_BUFFEREVENTS
  2077. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  2078. * mode. */
  2079. int
  2080. tor_tls_start_renegotiating(tor_tls_t *tls)
  2081. {
  2082. int r = SSL_renegotiate(tls->ssl);
  2083. if (r <= 0) {
  2084. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  2085. LD_HANDSHAKE);
  2086. }
  2087. return 0;
  2088. }
  2089. #endif
  2090. /** Client only: Renegotiate a TLS session. When finished, returns
  2091. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  2092. * TOR_TLS_WANTWRITE.
  2093. */
  2094. int
  2095. tor_tls_renegotiate(tor_tls_t *tls)
  2096. {
  2097. int r;
  2098. tor_assert(tls);
  2099. /* We could do server-initiated renegotiation too, but that would be tricky.
  2100. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  2101. tor_assert(!tls->isServer);
  2102. check_no_tls_errors();
  2103. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  2104. int r = SSL_renegotiate(tls->ssl);
  2105. if (r <= 0) {
  2106. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  2107. LD_HANDSHAKE);
  2108. }
  2109. tls->state = TOR_TLS_ST_RENEGOTIATE;
  2110. }
  2111. r = SSL_do_handshake(tls->ssl);
  2112. if (r == 1) {
  2113. tls->state = TOR_TLS_ST_OPEN;
  2114. return TOR_TLS_DONE;
  2115. } else
  2116. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  2117. LD_HANDSHAKE);
  2118. }
  2119. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  2120. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  2121. * or TOR_TLS_WANTWRITE.
  2122. */
  2123. int
  2124. tor_tls_shutdown(tor_tls_t *tls)
  2125. {
  2126. int r, err;
  2127. char buf[128];
  2128. tor_assert(tls);
  2129. tor_assert(tls->ssl);
  2130. check_no_tls_errors();
  2131. while (1) {
  2132. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  2133. /* If we've already called shutdown once to send a close message,
  2134. * we read until the other side has closed too.
  2135. */
  2136. do {
  2137. r = SSL_read(tls->ssl, buf, 128);
  2138. } while (r>0);
  2139. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  2140. LOG_INFO, LD_NET);
  2141. if (err == TOR_TLS_ZERORETURN_) {
  2142. tls->state = TOR_TLS_ST_GOTCLOSE;
  2143. /* fall through... */
  2144. } else {
  2145. return err;
  2146. }
  2147. }
  2148. r = SSL_shutdown(tls->ssl);
  2149. if (r == 1) {
  2150. /* If shutdown returns 1, the connection is entirely closed. */
  2151. tls->state = TOR_TLS_ST_CLOSED;
  2152. return TOR_TLS_DONE;
  2153. }
  2154. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  2155. LOG_INFO, LD_NET);
  2156. if (err == TOR_TLS_SYSCALL_) {
  2157. /* The underlying TCP connection closed while we were shutting down. */
  2158. tls->state = TOR_TLS_ST_CLOSED;
  2159. return TOR_TLS_DONE;
  2160. } else if (err == TOR_TLS_ZERORETURN_) {
  2161. /* The TLS connection says that it sent a shutdown record, but
  2162. * isn't done shutting down yet. Make sure that this hasn't
  2163. * happened before, then go back to the start of the function
  2164. * and try to read.
  2165. */
  2166. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  2167. tls->state == TOR_TLS_ST_SENTCLOSE) {
  2168. log_warn(LD_NET,
  2169. "TLS returned \"half-closed\" value while already half-closed");
  2170. return TOR_TLS_ERROR_MISC;
  2171. }
  2172. tls->state = TOR_TLS_ST_SENTCLOSE;
  2173. /* fall through ... */
  2174. } else {
  2175. return err;
  2176. }
  2177. } /* end loop */
  2178. }
  2179. /** Return true iff this TLS connection is authenticated.
  2180. */
  2181. int
  2182. tor_tls_peer_has_cert(tor_tls_t *tls)
  2183. {
  2184. X509 *cert;
  2185. cert = SSL_get_peer_certificate(tls->ssl);
  2186. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  2187. if (!cert)
  2188. return 0;
  2189. X509_free(cert);
  2190. return 1;
  2191. }
  2192. /** Return the peer certificate, or NULL if there isn't one. */
  2193. tor_x509_cert_t *
  2194. tor_tls_get_peer_cert(tor_tls_t *tls)
  2195. {
  2196. X509 *cert;
  2197. cert = SSL_get_peer_certificate(tls->ssl);
  2198. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  2199. if (!cert)
  2200. return NULL;
  2201. return tor_x509_cert_new(cert);
  2202. }
  2203. /** Warn that a certificate lifetime extends through a certain range. */
  2204. static void
  2205. log_cert_lifetime(int severity, const X509 *cert, const char *problem)
  2206. {
  2207. BIO *bio = NULL;
  2208. BUF_MEM *buf;
  2209. char *s1=NULL, *s2=NULL;
  2210. char mytime[33];
  2211. time_t now = time(NULL);
  2212. struct tm tm;
  2213. size_t n;
  2214. if (problem)
  2215. tor_log(severity, LD_GENERAL,
  2216. "Certificate %s. Either their clock is set wrong, or your clock "
  2217. "is wrong.",
  2218. problem);
  2219. if (!(bio = BIO_new(BIO_s_mem()))) {
  2220. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  2221. }
  2222. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  2223. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  2224. goto end;
  2225. }
  2226. BIO_get_mem_ptr(bio, &buf);
  2227. s1 = tor_strndup(buf->data, buf->length);
  2228. (void)BIO_reset(bio);
  2229. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  2230. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  2231. goto end;
  2232. }
  2233. BIO_get_mem_ptr(bio, &buf);
  2234. s2 = tor_strndup(buf->data, buf->length);
  2235. n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
  2236. if (n > 0) {
  2237. tor_log(severity, LD_GENERAL,
  2238. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  2239. s1,s2,mytime);
  2240. } else {
  2241. tor_log(severity, LD_GENERAL,
  2242. "(certificate lifetime runs from %s through %s. "
  2243. "Couldn't get your time.)",
  2244. s1, s2);
  2245. }
  2246. end:
  2247. /* Not expected to get invoked */
  2248. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  2249. if (bio)
  2250. BIO_free(bio);
  2251. tor_free(s1);
  2252. tor_free(s2);
  2253. }
  2254. /** Helper function: try to extract a link certificate and an identity
  2255. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  2256. * *<b>id_cert_out</b> respectively. Log all messages at level
  2257. * <b>severity</b>.
  2258. *
  2259. * Note that a reference is added to cert_out, so it needs to be
  2260. * freed. id_cert_out doesn't. */
  2261. static void
  2262. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  2263. X509 **cert_out, X509 **id_cert_out)
  2264. {
  2265. X509 *cert = NULL, *id_cert = NULL;
  2266. STACK_OF(X509) *chain = NULL;
  2267. int num_in_chain, i;
  2268. *cert_out = *id_cert_out = NULL;
  2269. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  2270. return;
  2271. *cert_out = cert;
  2272. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  2273. return;
  2274. num_in_chain = sk_X509_num(chain);
  2275. /* 1 means we're receiving (server-side), and it's just the id_cert.
  2276. * 2 means we're connecting (client-side), and it's both the link
  2277. * cert and the id_cert.
  2278. */
  2279. if (num_in_chain < 1) {
  2280. log_fn(severity,LD_PROTOCOL,
  2281. "Unexpected number of certificates in chain (%d)",
  2282. num_in_chain);
  2283. return;
  2284. }
  2285. for (i=0; i<num_in_chain; ++i) {
  2286. id_cert = sk_X509_value(chain, i);
  2287. if (X509_cmp(id_cert, cert) != 0)
  2288. break;
  2289. }
  2290. *id_cert_out = id_cert;
  2291. }
  2292. /** If the provided tls connection is authenticated and has a
  2293. * certificate chain that is currently valid and signed, then set
  2294. * *<b>identity_key</b> to the identity certificate's key and return
  2295. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  2296. */
  2297. int
  2298. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
  2299. {
  2300. X509 *cert = NULL, *id_cert = NULL;
  2301. EVP_PKEY *id_pkey = NULL;
  2302. RSA *rsa;
  2303. int r = -1;
  2304. check_no_tls_errors();
  2305. *identity_key = NULL;
  2306. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  2307. if (!cert)
  2308. goto done;
  2309. if (!id_cert) {
  2310. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  2311. goto done;
  2312. }
  2313. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  2314. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  2315. X509_verify(cert, id_pkey) <= 0) {
  2316. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  2317. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  2318. goto done;
  2319. }
  2320. rsa = EVP_PKEY_get1_RSA(id_pkey);
  2321. if (!rsa)
  2322. goto done;
  2323. *identity_key = crypto_new_pk_from_rsa_(rsa);
  2324. r = 0;
  2325. done:
  2326. if (cert)
  2327. X509_free(cert);
  2328. if (id_pkey)
  2329. EVP_PKEY_free(id_pkey);
  2330. /* This should never get invoked, but let's make sure in case OpenSSL
  2331. * acts unexpectedly. */
  2332. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  2333. return r;
  2334. }
  2335. /** Check whether the certificate set on the connection <b>tls</b> is expired
  2336. * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
  2337. * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
  2338. *
  2339. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  2340. */
  2341. int
  2342. tor_tls_check_lifetime(int severity, tor_tls_t *tls,
  2343. int past_tolerance, int future_tolerance)
  2344. {
  2345. X509 *cert;
  2346. int r = -1;
  2347. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  2348. goto done;
  2349. if (check_cert_lifetime_internal(severity, cert,
  2350. past_tolerance, future_tolerance) < 0)
  2351. goto done;
  2352. r = 0;
  2353. done:
  2354. if (cert)
  2355. X509_free(cert);
  2356. /* Not expected to get invoked */
  2357. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  2358. return r;
  2359. }
  2360. /** Helper: check whether <b>cert</b> is expired give or take
  2361. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  2362. * <b>future_tolerance</b> seconds. If it is live, return 0. If it is not
  2363. * live, log a message and return -1. */
  2364. static int
  2365. check_cert_lifetime_internal(int severity, const X509 *cert,
  2366. int past_tolerance, int future_tolerance)
  2367. {
  2368. time_t now, t;
  2369. now = time(NULL);
  2370. t = now + future_tolerance;
  2371. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  2372. log_cert_lifetime(severity, cert, "not yet valid");
  2373. return -1;
  2374. }
  2375. t = now - past_tolerance;
  2376. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  2377. log_cert_lifetime(severity, cert, "already expired");
  2378. return -1;
  2379. }
  2380. return 0;
  2381. }
  2382. /** Return the number of bytes available for reading from <b>tls</b>.
  2383. */
  2384. int
  2385. tor_tls_get_pending_bytes(tor_tls_t *tls)
  2386. {
  2387. tor_assert(tls);
  2388. return SSL_pending(tls->ssl);
  2389. }
  2390. /** If <b>tls</b> requires that the next write be of a particular size,
  2391. * return that size. Otherwise, return 0. */
  2392. size_t
  2393. tor_tls_get_forced_write_size(tor_tls_t *tls)
  2394. {
  2395. return tls->wantwrite_n;
  2396. }
  2397. /** Sets n_read and n_written to the number of bytes read and written,
  2398. * respectively, on the raw socket used by <b>tls</b> since the last time this
  2399. * function was called on <b>tls</b>. */
  2400. void
  2401. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  2402. {
  2403. BIO *wbio, *tmpbio;
  2404. unsigned long r, w;
  2405. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  2406. /* We want the number of bytes actually for real written. Unfortunately,
  2407. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  2408. * which makes the answer turn out wrong. Let's cope with that. Note
  2409. * that this approach will fail if we ever replace tls->ssl's BIOs with
  2410. * buffering bios for reasons of our own. As an alternative, we could
  2411. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  2412. * that would be tempting fate. */
  2413. wbio = SSL_get_wbio(tls->ssl);
  2414. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  2415. wbio = tmpbio;
  2416. w = BIO_number_written(wbio);
  2417. /* We are ok with letting these unsigned ints go "negative" here:
  2418. * If we wrapped around, this should still give us the right answer, unless
  2419. * we wrapped around by more than ULONG_MAX since the last time we called
  2420. * this function.
  2421. */
  2422. *n_read = (size_t)(r - tls->last_read_count);
  2423. *n_written = (size_t)(w - tls->last_write_count);
  2424. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  2425. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  2426. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  2427. r, tls->last_read_count, w, tls->last_write_count);
  2428. }
  2429. total_bytes_written_by_tls += *n_written;
  2430. tls->last_read_count = r;
  2431. tls->last_write_count = w;
  2432. }
  2433. /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
  2434. * it to send. Used to track whether our TLS records are getting too tiny. */
  2435. MOCK_IMPL(double,
  2436. tls_get_write_overhead_ratio,(void))
  2437. {
  2438. if (total_bytes_written_over_tls == 0)
  2439. return 1.0;
  2440. return U64_TO_DBL(total_bytes_written_by_tls) /
  2441. U64_TO_DBL(total_bytes_written_over_tls);
  2442. }
  2443. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  2444. * errors, log an error message. */
  2445. void
  2446. check_no_tls_errors_(const char *fname, int line)
  2447. {
  2448. if (ERR_peek_error() == 0)
  2449. return;
  2450. log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  2451. tor_fix_source_file(fname), line);
  2452. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  2453. }
  2454. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  2455. * TLS handshake. Output is undefined if the handshake isn't finished. */
  2456. int
  2457. tor_tls_used_v1_handshake(tor_tls_t *tls)
  2458. {
  2459. #if defined(V2_HANDSHAKE_SERVER) && defined(V2_HANDSHAKE_CLIENT)
  2460. return ! tls->wasV2Handshake;
  2461. #else
  2462. if (tls->isServer) {
  2463. # ifdef V2_HANDSHAKE_SERVER
  2464. return ! tls->wasV2Handshake;
  2465. # endif
  2466. } else {
  2467. # ifdef V2_HANDSHAKE_CLIENT
  2468. return ! tls->wasV2Handshake;
  2469. # endif
  2470. }
  2471. return 1;
  2472. #endif
  2473. }
  2474. /** Return true iff <b>name</b> is a DN of a kind that could only
  2475. * occur in a v3-handshake-indicating certificate */
  2476. static int
  2477. dn_indicates_v3_cert(X509_NAME *name)
  2478. {
  2479. #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
  2480. (void)name;
  2481. return 0;
  2482. #else
  2483. X509_NAME_ENTRY *entry;
  2484. int n_entries;
  2485. ASN1_OBJECT *obj;
  2486. ASN1_STRING *str;
  2487. unsigned char *s;
  2488. int len, r;
  2489. n_entries = X509_NAME_entry_count(name);
  2490. if (n_entries != 1)
  2491. return 1; /* More than one entry in the DN. */
  2492. entry = X509_NAME_get_entry(name, 0);
  2493. obj = X509_NAME_ENTRY_get_object(entry);
  2494. if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
  2495. return 1; /* The entry isn't a commonName. */
  2496. str = X509_NAME_ENTRY_get_data(entry);
  2497. len = ASN1_STRING_to_UTF8(&s, str);
  2498. if (len < 0)
  2499. return 0;
  2500. r = fast_memneq(s + len - 4, ".net", 4);
  2501. OPENSSL_free(s);
  2502. return r;
  2503. #endif
  2504. }
  2505. /** Return true iff the peer certificate we're received on <b>tls</b>
  2506. * indicates that this connection should use the v3 (in-protocol)
  2507. * authentication handshake.
  2508. *
  2509. * Only the connection initiator should use this, and only once the initial
  2510. * handshake is done; the responder detects a v1 handshake by cipher types,
  2511. * and a v3/v2 handshake by Versions cell vs renegotiation.
  2512. */
  2513. int
  2514. tor_tls_received_v3_certificate(tor_tls_t *tls)
  2515. {
  2516. check_no_tls_errors();
  2517. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  2518. EVP_PKEY *key = NULL;
  2519. X509_NAME *issuer_name, *subject_name;
  2520. int is_v3 = 0;
  2521. if (!cert) {
  2522. log_warn(LD_BUG, "Called on a connection with no peer certificate");
  2523. goto done;
  2524. }
  2525. subject_name = X509_get_subject_name(cert);
  2526. issuer_name = X509_get_issuer_name(cert);
  2527. if (X509_name_cmp(subject_name, issuer_name) == 0) {
  2528. is_v3 = 1; /* purportedly self signed */
  2529. goto done;
  2530. }
  2531. if (dn_indicates_v3_cert(subject_name) ||
  2532. dn_indicates_v3_cert(issuer_name)) {
  2533. is_v3 = 1; /* DN is fancy */
  2534. goto done;
  2535. }
  2536. key = X509_get_pubkey(cert);
  2537. if (EVP_PKEY_bits(key) != 1024 ||
  2538. EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
  2539. is_v3 = 1; /* Key is fancy */
  2540. goto done;
  2541. }
  2542. done:
  2543. tls_log_errors(tls, LOG_WARN, LD_NET, "checking for a v3 cert");
  2544. if (key)
  2545. EVP_PKEY_free(key);
  2546. if (cert)
  2547. X509_free(cert);
  2548. return is_v3;
  2549. }
  2550. /** Return the number of server handshakes that we've noticed doing on
  2551. * <b>tls</b>. */
  2552. int
  2553. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  2554. {
  2555. return tls->server_handshake_count;
  2556. }
  2557. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  2558. * request it was waiting for. */
  2559. int
  2560. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  2561. {
  2562. return tls->got_renegotiate;
  2563. }
  2564. /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
  2565. * the v3 handshake to prove that the client knows the TLS secrets for the
  2566. * connection <b>tls</b>. Return 0 on success, -1 on failure.
  2567. */
  2568. int
  2569. tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
  2570. {
  2571. #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
  2572. char buf[128];
  2573. size_t len;
  2574. tor_assert(tls);
  2575. tor_assert(tls->ssl);
  2576. tor_assert(tls->ssl->s3);
  2577. tor_assert(tls->ssl->session);
  2578. /*
  2579. The value is an HMAC, using the TLS master key as the HMAC key, of
  2580. client_random | server_random | TLSSECRET_MAGIC
  2581. */
  2582. memcpy(buf + 0, tls->ssl->s3->client_random, 32);
  2583. memcpy(buf + 32, tls->ssl->s3->server_random, 32);
  2584. memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
  2585. len = 64 + strlen(TLSSECRET_MAGIC) + 1;
  2586. crypto_hmac_sha256((char*)secrets_out,
  2587. (char*)tls->ssl->session->master_key,
  2588. tls->ssl->session->master_key_length,
  2589. buf, len);
  2590. memwipe(buf, 0, sizeof(buf));
  2591. return 0;
  2592. }
  2593. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  2594. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  2595. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  2596. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  2597. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  2598. void
  2599. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  2600. size_t *rbuf_capacity, size_t *rbuf_bytes,
  2601. size_t *wbuf_capacity, size_t *wbuf_bytes)
  2602. {
  2603. if (tls->ssl->s3->rbuf.buf)
  2604. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  2605. else
  2606. *rbuf_capacity = 0;
  2607. if (tls->ssl->s3->wbuf.buf)
  2608. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  2609. else
  2610. *wbuf_capacity = 0;
  2611. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  2612. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  2613. }
  2614. #ifdef USE_BUFFEREVENTS
  2615. /** Construct and return an TLS-encrypting bufferevent to send data over
  2616. * <b>socket</b>, which must match the socket of the underlying bufferevent
  2617. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  2618. *
  2619. * This function will either create a filtering bufferevent that wraps around
  2620. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  2621. * uses the <b>tls</b> to talk to the network directly. Do not use
  2622. * <b>bufev_in</b> after calling this function.
  2623. *
  2624. * The connection will start out doing a server handshake if <b>receiving</b>
  2625. * is strue, and a client handshake otherwise.
  2626. *
  2627. * Returns NULL on failure.
  2628. */
  2629. struct bufferevent *
  2630. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  2631. evutil_socket_t socket, int receiving,
  2632. int filter)
  2633. {
  2634. struct bufferevent *out;
  2635. const enum bufferevent_ssl_state state = receiving ?
  2636. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  2637. if (filter || tor_libevent_using_iocp_bufferevents()) {
  2638. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  2639. means that the SSL will get freed too.
  2640. This increment makes our SSL usage not-threadsafe, BTW. We should
  2641. see if we're allowed to use CRYPTO_add from outside openssl. */
  2642. tls->ssl->references += 1;
  2643. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  2644. bufev_in,
  2645. tls->ssl,
  2646. state,
  2647. BEV_OPT_DEFER_CALLBACKS|
  2648. BEV_OPT_CLOSE_ON_FREE);
  2649. /* Tell the underlying bufferevent when to accept more data from the SSL
  2650. filter (only when it's got less than 32K to write), and when to notify
  2651. the SSL filter that it could write more (when it drops under 24K). */
  2652. bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
  2653. } else {
  2654. if (bufev_in) {
  2655. evutil_socket_t s = bufferevent_getfd(bufev_in);
  2656. tor_assert(s == -1 || s == socket);
  2657. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  2658. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  2659. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  2660. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  2661. bufferevent_free(bufev_in);
  2662. }
  2663. /* Current versions (as of 2.0.x) of Libevent need to defer
  2664. * bufferevent_openssl callbacks, or else our callback functions will
  2665. * get called reentrantly, which is bad for us.
  2666. */
  2667. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  2668. socket,
  2669. tls->ssl,
  2670. state,
  2671. BEV_OPT_DEFER_CALLBACKS);
  2672. }
  2673. tls->state = TOR_TLS_ST_BUFFEREVENT;
  2674. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  2675. * clear flags. */
  2676. tor_tls_unblock_renegotiation(tls);
  2677. return out;
  2678. }
  2679. #endif