s_client.c 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564
  1. /*
  2. * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright 2005 Nokia. All rights reserved.
  4. *
  5. * Licensed under the OpenSSL license (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include "e_os.h"
  11. #include <ctype.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <errno.h>
  16. #include <openssl/e_os2.h>
  17. #ifndef OPENSSL_NO_SOCK
  18. /*
  19. * With IPv6, it looks like Digital has mixed up the proper order of
  20. * recursive header file inclusion, resulting in the compiler complaining
  21. * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
  22. * needed to have fileno() declared correctly... So let's define u_int
  23. */
  24. #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
  25. # define __U_INT
  26. typedef unsigned int u_int;
  27. #endif
  28. #include "apps.h"
  29. #include "progs.h"
  30. #include <openssl/x509.h>
  31. #include <openssl/ssl.h>
  32. #include <openssl/err.h>
  33. #include <openssl/pem.h>
  34. #include <openssl/rand.h>
  35. #include <openssl/ocsp.h>
  36. #include <openssl/bn.h>
  37. #include <openssl/async.h>
  38. #ifndef OPENSSL_NO_SRP
  39. # include <openssl/srp.h>
  40. #endif
  41. #ifndef OPENSSL_NO_CT
  42. # include <openssl/ct.h>
  43. #endif
  44. #include "s_apps.h"
  45. #include "timeouts.h"
  46. #include "internal/sockets.h"
  47. #if defined(__has_feature)
  48. # if __has_feature(memory_sanitizer)
  49. # include <sanitizer/msan_interface.h>
  50. # endif
  51. #endif
  52. #undef BUFSIZZ
  53. #define BUFSIZZ 1024*8
  54. #define S_CLIENT_IRC_READ_TIMEOUT 8
  55. static char *prog;
  56. static int c_debug = 0;
  57. static int c_showcerts = 0;
  58. static char *keymatexportlabel = NULL;
  59. static int keymatexportlen = 20;
  60. static BIO *bio_c_out = NULL;
  61. static int c_quiet = 0;
  62. static char *sess_out = NULL;
  63. static SSL_SESSION *psksess = NULL;
  64. static void print_stuff(BIO *berr, SSL *con, int full);
  65. #ifndef OPENSSL_NO_OCSP
  66. static int ocsp_resp_cb(SSL *s, void *arg);
  67. #endif
  68. static int ldap_ExtendedResponse_parse(const char *buf, long rem);
  69. static int is_dNS_name(const char *host);
  70. static int saved_errno;
  71. static void save_errno(void)
  72. {
  73. saved_errno = errno;
  74. errno = 0;
  75. }
  76. static int restore_errno(void)
  77. {
  78. int ret = errno;
  79. errno = saved_errno;
  80. return ret;
  81. }
  82. static void do_ssl_shutdown(SSL *ssl)
  83. {
  84. int ret;
  85. do {
  86. /* We only do unidirectional shutdown */
  87. ret = SSL_shutdown(ssl);
  88. if (ret < 0) {
  89. switch (SSL_get_error(ssl, ret)) {
  90. case SSL_ERROR_WANT_READ:
  91. case SSL_ERROR_WANT_WRITE:
  92. case SSL_ERROR_WANT_ASYNC:
  93. case SSL_ERROR_WANT_ASYNC_JOB:
  94. /* We just do busy waiting. Nothing clever */
  95. continue;
  96. }
  97. ret = 0;
  98. }
  99. } while (ret < 0);
  100. }
  101. /* Default PSK identity and key */
  102. static char *psk_identity = "Client_identity";
  103. #ifndef OPENSSL_NO_PSK
  104. static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
  105. unsigned int max_identity_len,
  106. unsigned char *psk,
  107. unsigned int max_psk_len)
  108. {
  109. int ret;
  110. long key_len;
  111. unsigned char *key;
  112. if (c_debug)
  113. BIO_printf(bio_c_out, "psk_client_cb\n");
  114. if (!hint) {
  115. /* no ServerKeyExchange message */
  116. if (c_debug)
  117. BIO_printf(bio_c_out,
  118. "NULL received PSK identity hint, continuing anyway\n");
  119. } else if (c_debug) {
  120. BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
  121. }
  122. /*
  123. * lookup PSK identity and PSK key based on the given identity hint here
  124. */
  125. ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
  126. if (ret < 0 || (unsigned int)ret > max_identity_len)
  127. goto out_err;
  128. if (c_debug)
  129. BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
  130. ret);
  131. /* convert the PSK key to binary */
  132. key = OPENSSL_hexstr2buf(psk_key, &key_len);
  133. if (key == NULL) {
  134. BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
  135. psk_key);
  136. return 0;
  137. }
  138. if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
  139. BIO_printf(bio_err,
  140. "psk buffer of callback is too small (%d) for key (%ld)\n",
  141. max_psk_len, key_len);
  142. OPENSSL_free(key);
  143. return 0;
  144. }
  145. memcpy(psk, key, key_len);
  146. OPENSSL_free(key);
  147. if (c_debug)
  148. BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
  149. return key_len;
  150. out_err:
  151. if (c_debug)
  152. BIO_printf(bio_err, "Error in PSK client callback\n");
  153. return 0;
  154. }
  155. #endif
  156. const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
  157. const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
  158. static int psk_use_session_cb(SSL *s, const EVP_MD *md,
  159. const unsigned char **id, size_t *idlen,
  160. SSL_SESSION **sess)
  161. {
  162. SSL_SESSION *usesess = NULL;
  163. const SSL_CIPHER *cipher = NULL;
  164. if (psksess != NULL) {
  165. SSL_SESSION_up_ref(psksess);
  166. usesess = psksess;
  167. } else {
  168. long key_len;
  169. unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
  170. if (key == NULL) {
  171. BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
  172. psk_key);
  173. return 0;
  174. }
  175. /* We default to SHA-256 */
  176. cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
  177. if (cipher == NULL) {
  178. BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
  179. OPENSSL_free(key);
  180. return 0;
  181. }
  182. usesess = SSL_SESSION_new();
  183. if (usesess == NULL
  184. || !SSL_SESSION_set1_master_key(usesess, key, key_len)
  185. || !SSL_SESSION_set_cipher(usesess, cipher)
  186. || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
  187. OPENSSL_free(key);
  188. goto err;
  189. }
  190. OPENSSL_free(key);
  191. }
  192. cipher = SSL_SESSION_get0_cipher(usesess);
  193. if (cipher == NULL)
  194. goto err;
  195. if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
  196. /* PSK not usable, ignore it */
  197. *id = NULL;
  198. *idlen = 0;
  199. *sess = NULL;
  200. SSL_SESSION_free(usesess);
  201. } else {
  202. *sess = usesess;
  203. *id = (unsigned char *)psk_identity;
  204. *idlen = strlen(psk_identity);
  205. }
  206. return 1;
  207. err:
  208. SSL_SESSION_free(usesess);
  209. return 0;
  210. }
  211. /* This is a context that we pass to callbacks */
  212. typedef struct tlsextctx_st {
  213. BIO *biodebug;
  214. int ack;
  215. } tlsextctx;
  216. static int ssl_servername_cb(SSL *s, int *ad, void *arg)
  217. {
  218. tlsextctx *p = (tlsextctx *) arg;
  219. const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
  220. if (SSL_get_servername_type(s) != -1)
  221. p->ack = !SSL_session_reused(s) && hn != NULL;
  222. else
  223. BIO_printf(bio_err, "Can't use SSL_get_servername\n");
  224. return SSL_TLSEXT_ERR_OK;
  225. }
  226. #ifndef OPENSSL_NO_SRP
  227. /* This is a context that we pass to all callbacks */
  228. typedef struct srp_arg_st {
  229. char *srppassin;
  230. char *srplogin;
  231. int msg; /* copy from c_msg */
  232. int debug; /* copy from c_debug */
  233. int amp; /* allow more groups */
  234. int strength; /* minimal size for N */
  235. } SRP_ARG;
  236. # define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
  237. static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
  238. {
  239. BN_CTX *bn_ctx = BN_CTX_new();
  240. BIGNUM *p = BN_new();
  241. BIGNUM *r = BN_new();
  242. int ret =
  243. g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
  244. BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
  245. p != NULL && BN_rshift1(p, N) &&
  246. /* p = (N-1)/2 */
  247. BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
  248. r != NULL &&
  249. /* verify g^((N-1)/2) == -1 (mod N) */
  250. BN_mod_exp(r, g, p, N, bn_ctx) &&
  251. BN_add_word(r, 1) && BN_cmp(r, N) == 0;
  252. BN_free(r);
  253. BN_free(p);
  254. BN_CTX_free(bn_ctx);
  255. return ret;
  256. }
  257. /*-
  258. * This callback is used here for two purposes:
  259. * - extended debugging
  260. * - making some primality tests for unknown groups
  261. * The callback is only called for a non default group.
  262. *
  263. * An application does not need the call back at all if
  264. * only the standard groups are used. In real life situations,
  265. * client and server already share well known groups,
  266. * thus there is no need to verify them.
  267. * Furthermore, in case that a server actually proposes a group that
  268. * is not one of those defined in RFC 5054, it is more appropriate
  269. * to add the group to a static list and then compare since
  270. * primality tests are rather cpu consuming.
  271. */
  272. static int ssl_srp_verify_param_cb(SSL *s, void *arg)
  273. {
  274. SRP_ARG *srp_arg = (SRP_ARG *)arg;
  275. BIGNUM *N = NULL, *g = NULL;
  276. if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
  277. return 0;
  278. if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
  279. BIO_printf(bio_err, "SRP parameters:\n");
  280. BIO_printf(bio_err, "\tN=");
  281. BN_print(bio_err, N);
  282. BIO_printf(bio_err, "\n\tg=");
  283. BN_print(bio_err, g);
  284. BIO_printf(bio_err, "\n");
  285. }
  286. if (SRP_check_known_gN_param(g, N))
  287. return 1;
  288. if (srp_arg->amp == 1) {
  289. if (srp_arg->debug)
  290. BIO_printf(bio_err,
  291. "SRP param N and g are not known params, going to check deeper.\n");
  292. /*
  293. * The srp_moregroups is a real debugging feature. Implementors
  294. * should rather add the value to the known ones. The minimal size
  295. * has already been tested.
  296. */
  297. if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
  298. return 1;
  299. }
  300. BIO_printf(bio_err, "SRP param N and g rejected.\n");
  301. return 0;
  302. }
  303. # define PWD_STRLEN 1024
  304. static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
  305. {
  306. SRP_ARG *srp_arg = (SRP_ARG *)arg;
  307. char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
  308. PW_CB_DATA cb_tmp;
  309. int l;
  310. cb_tmp.password = (char *)srp_arg->srppassin;
  311. cb_tmp.prompt_info = "SRP user";
  312. if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
  313. BIO_printf(bio_err, "Can't read Password\n");
  314. OPENSSL_free(pass);
  315. return NULL;
  316. }
  317. *(pass + l) = '\0';
  318. return pass;
  319. }
  320. #endif
  321. #ifndef OPENSSL_NO_NEXTPROTONEG
  322. /* This the context that we pass to next_proto_cb */
  323. typedef struct tlsextnextprotoctx_st {
  324. unsigned char *data;
  325. size_t len;
  326. int status;
  327. } tlsextnextprotoctx;
  328. static tlsextnextprotoctx next_proto;
  329. static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
  330. const unsigned char *in, unsigned int inlen,
  331. void *arg)
  332. {
  333. tlsextnextprotoctx *ctx = arg;
  334. if (!c_quiet) {
  335. /* We can assume that |in| is syntactically valid. */
  336. unsigned i;
  337. BIO_printf(bio_c_out, "Protocols advertised by server: ");
  338. for (i = 0; i < inlen;) {
  339. if (i)
  340. BIO_write(bio_c_out, ", ", 2);
  341. BIO_write(bio_c_out, &in[i + 1], in[i]);
  342. i += in[i] + 1;
  343. }
  344. BIO_write(bio_c_out, "\n", 1);
  345. }
  346. ctx->status =
  347. SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
  348. return SSL_TLSEXT_ERR_OK;
  349. }
  350. #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
  351. static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
  352. const unsigned char *in, size_t inlen,
  353. int *al, void *arg)
  354. {
  355. char pem_name[100];
  356. unsigned char ext_buf[4 + 65536];
  357. /* Reconstruct the type/len fields prior to extension data */
  358. inlen &= 0xffff; /* for formal memcmpy correctness */
  359. ext_buf[0] = (unsigned char)(ext_type >> 8);
  360. ext_buf[1] = (unsigned char)(ext_type);
  361. ext_buf[2] = (unsigned char)(inlen >> 8);
  362. ext_buf[3] = (unsigned char)(inlen);
  363. memcpy(ext_buf + 4, in, inlen);
  364. BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
  365. ext_type);
  366. PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
  367. return 1;
  368. }
  369. /*
  370. * Hex decoder that tolerates optional whitespace. Returns number of bytes
  371. * produced, advances inptr to end of input string.
  372. */
  373. static ossl_ssize_t hexdecode(const char **inptr, void *result)
  374. {
  375. unsigned char **out = (unsigned char **)result;
  376. const char *in = *inptr;
  377. unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
  378. unsigned char *cp = ret;
  379. uint8_t byte;
  380. int nibble = 0;
  381. if (ret == NULL)
  382. return -1;
  383. for (byte = 0; *in; ++in) {
  384. int x;
  385. if (isspace(_UC(*in)))
  386. continue;
  387. x = OPENSSL_hexchar2int(*in);
  388. if (x < 0) {
  389. OPENSSL_free(ret);
  390. return 0;
  391. }
  392. byte |= (char)x;
  393. if ((nibble ^= 1) == 0) {
  394. *cp++ = byte;
  395. byte = 0;
  396. } else {
  397. byte <<= 4;
  398. }
  399. }
  400. if (nibble != 0) {
  401. OPENSSL_free(ret);
  402. return 0;
  403. }
  404. *inptr = in;
  405. return cp - (*out = ret);
  406. }
  407. /*
  408. * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
  409. * inptr to next field skipping leading whitespace.
  410. */
  411. static ossl_ssize_t checked_uint8(const char **inptr, void *out)
  412. {
  413. uint8_t *result = (uint8_t *)out;
  414. const char *in = *inptr;
  415. char *endp;
  416. long v;
  417. int e;
  418. save_errno();
  419. v = strtol(in, &endp, 10);
  420. e = restore_errno();
  421. if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
  422. endp == in || !isspace(_UC(*endp)) ||
  423. v != (*result = (uint8_t) v)) {
  424. return -1;
  425. }
  426. for (in = endp; isspace(_UC(*in)); ++in)
  427. continue;
  428. *inptr = in;
  429. return 1;
  430. }
  431. struct tlsa_field {
  432. void *var;
  433. const char *name;
  434. ossl_ssize_t (*parser)(const char **, void *);
  435. };
  436. static int tlsa_import_rr(SSL *con, const char *rrdata)
  437. {
  438. /* Not necessary to re-init these values; the "parsers" do that. */
  439. static uint8_t usage;
  440. static uint8_t selector;
  441. static uint8_t mtype;
  442. static unsigned char *data;
  443. static struct tlsa_field tlsa_fields[] = {
  444. { &usage, "usage", checked_uint8 },
  445. { &selector, "selector", checked_uint8 },
  446. { &mtype, "mtype", checked_uint8 },
  447. { &data, "data", hexdecode },
  448. { NULL, }
  449. };
  450. struct tlsa_field *f;
  451. int ret;
  452. const char *cp = rrdata;
  453. ossl_ssize_t len = 0;
  454. for (f = tlsa_fields; f->var; ++f) {
  455. /* Returns number of bytes produced, advances cp to next field */
  456. if ((len = f->parser(&cp, f->var)) <= 0) {
  457. BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
  458. prog, f->name, rrdata);
  459. return 0;
  460. }
  461. }
  462. /* The data field is last, so len is its length */
  463. ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
  464. OPENSSL_free(data);
  465. if (ret == 0) {
  466. ERR_print_errors(bio_err);
  467. BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
  468. prog, rrdata);
  469. return 0;
  470. }
  471. if (ret < 0) {
  472. ERR_print_errors(bio_err);
  473. BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
  474. prog, rrdata);
  475. return 0;
  476. }
  477. return ret;
  478. }
  479. static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
  480. {
  481. int num = sk_OPENSSL_STRING_num(rrset);
  482. int count = 0;
  483. int i;
  484. for (i = 0; i < num; ++i) {
  485. char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
  486. if (tlsa_import_rr(con, rrdata) > 0)
  487. ++count;
  488. }
  489. return count > 0;
  490. }
  491. typedef enum OPTION_choice {
  492. OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
  493. OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
  494. OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
  495. OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
  496. OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
  497. OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
  498. OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
  499. OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
  500. OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
  501. OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
  502. OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
  503. #ifndef OPENSSL_NO_SRP
  504. OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
  505. OPT_SRP_MOREGROUPS,
  506. #endif
  507. OPT_SSL3, OPT_SSL_CONFIG,
  508. OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
  509. OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
  510. OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
  511. OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE,
  512. OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN,
  513. OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
  514. OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
  515. OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
  516. OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
  517. OPT_V_ENUM,
  518. OPT_X_ENUM,
  519. OPT_S_ENUM,
  520. OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_DANE_TLSA_DOMAIN,
  521. #ifndef OPENSSL_NO_CT
  522. OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
  523. #endif
  524. OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
  525. OPT_ENABLE_PHA,
  526. OPT_SCTP_LABEL_BUG,
  527. OPT_R_ENUM
  528. } OPTION_CHOICE;
  529. const OPTIONS s_client_options[] = {
  530. {"help", OPT_HELP, '-', "Display this summary"},
  531. {"host", OPT_HOST, 's', "Use -connect instead"},
  532. {"port", OPT_PORT, 'p', "Use -connect instead"},
  533. {"connect", OPT_CONNECT, 's',
  534. "TCP/IP where to connect (default is :" PORT ")"},
  535. {"bind", OPT_BIND, 's', "bind local address for connection"},
  536. {"proxy", OPT_PROXY, 's',
  537. "Connect to via specified proxy to the real server"},
  538. #ifdef AF_UNIX
  539. {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
  540. #endif
  541. {"4", OPT_4, '-', "Use IPv4 only"},
  542. #ifdef AF_INET6
  543. {"6", OPT_6, '-', "Use IPv6 only"},
  544. #endif
  545. {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
  546. {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"},
  547. {"certform", OPT_CERTFORM, 'F',
  548. "Certificate format (PEM or DER) PEM default"},
  549. {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
  550. {"key", OPT_KEY, 's', "Private key file to use, if not in -cert file"},
  551. {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
  552. {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
  553. {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
  554. {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
  555. {"no-CAfile", OPT_NOCAFILE, '-',
  556. "Do not load the default certificates file"},
  557. {"no-CApath", OPT_NOCAPATH, '-',
  558. "Do not load certificates from the default certificates directory"},
  559. {"requestCAfile", OPT_REQCAFILE, '<',
  560. "PEM format file of CA names to send to the server"},
  561. {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
  562. {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
  563. "DANE TLSA rrdata presentation form"},
  564. {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
  565. "Disable name checks when matching DANE-EE(3) TLSA records"},
  566. {"reconnect", OPT_RECONNECT, '-',
  567. "Drop and re-make the connection with the same Session-ID"},
  568. {"showcerts", OPT_SHOWCERTS, '-',
  569. "Show all certificates sent by the server"},
  570. {"debug", OPT_DEBUG, '-', "Extra output"},
  571. {"msg", OPT_MSG, '-', "Show protocol messages"},
  572. {"msgfile", OPT_MSGFILE, '>',
  573. "File to send output of -msg or -trace, instead of stdout"},
  574. {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
  575. {"state", OPT_STATE, '-', "Print the ssl states"},
  576. {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
  577. {"quiet", OPT_QUIET, '-', "No s_client output"},
  578. {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
  579. {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
  580. {"starttls", OPT_STARTTLS, 's',
  581. "Use the appropriate STARTTLS command before starting TLS"},
  582. {"xmpphost", OPT_XMPPHOST, 's',
  583. "Alias of -name option for \"-starttls xmpp[-server]\""},
  584. OPT_R_OPTIONS,
  585. {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
  586. {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
  587. #ifndef OPENSSL_NO_SRTP
  588. {"use_srtp", OPT_USE_SRTP, 's',
  589. "Offer SRTP key management with a colon-separated profile list"},
  590. #endif
  591. {"keymatexport", OPT_KEYMATEXPORT, 's',
  592. "Export keying material using label"},
  593. {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
  594. "Export len bytes of keying material (default 20)"},
  595. {"maxfraglen", OPT_MAXFRAGLEN, 'p',
  596. "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
  597. {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
  598. {"name", OPT_PROTOHOST, 's',
  599. "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
  600. {"CRL", OPT_CRL, '<', "CRL file to use"},
  601. {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
  602. {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
  603. {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
  604. "Close connection on verification error"},
  605. {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
  606. {"brief", OPT_BRIEF, '-',
  607. "Restrict output to brief summary of connection parameters"},
  608. {"prexit", OPT_PREXIT, '-',
  609. "Print session information when the program exits"},
  610. {"security_debug", OPT_SECURITY_DEBUG, '-',
  611. "Enable security debug messages"},
  612. {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
  613. "Output more security debug output"},
  614. {"cert_chain", OPT_CERT_CHAIN, '<',
  615. "Certificate chain file (in PEM format)"},
  616. {"chainCApath", OPT_CHAINCAPATH, '/',
  617. "Use dir as certificate store path to build CA certificate chain"},
  618. {"verifyCApath", OPT_VERIFYCAPATH, '/',
  619. "Use dir as certificate store path to verify CA certificate"},
  620. {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
  621. {"chainCAfile", OPT_CHAINCAFILE, '<',
  622. "CA file for certificate chain (PEM format)"},
  623. {"verifyCAfile", OPT_VERIFYCAFILE, '<',
  624. "CA file for certificate verification (PEM format)"},
  625. {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
  626. {"servername", OPT_SERVERNAME, 's',
  627. "Set TLS extension servername (SNI) in ClientHello (default)"},
  628. {"noservername", OPT_NOSERVERNAME, '-',
  629. "Do not send the server name (SNI) extension in the ClientHello"},
  630. {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
  631. "Hex dump of all TLS extensions received"},
  632. #ifndef OPENSSL_NO_OCSP
  633. {"status", OPT_STATUS, '-', "Request certificate status from server"},
  634. #endif
  635. {"serverinfo", OPT_SERVERINFO, 's',
  636. "types Send empty ClientHello extensions (comma-separated numbers)"},
  637. {"alpn", OPT_ALPN, 's',
  638. "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
  639. {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
  640. {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified configuration file"},
  641. {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
  642. {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
  643. "Size used to split data for encrypt pipelines"},
  644. {"max_pipelines", OPT_MAX_PIPELINES, 'p',
  645. "Maximum number of encrypt/decrypt pipelines to be used"},
  646. {"read_buf", OPT_READ_BUF, 'p',
  647. "Default read buffer size to be used for connections"},
  648. OPT_S_OPTIONS,
  649. OPT_V_OPTIONS,
  650. OPT_X_OPTIONS,
  651. #ifndef OPENSSL_NO_SSL3
  652. {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
  653. #endif
  654. #ifndef OPENSSL_NO_TLS1
  655. {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
  656. #endif
  657. #ifndef OPENSSL_NO_TLS1_1
  658. {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
  659. #endif
  660. #ifndef OPENSSL_NO_TLS1_2
  661. {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
  662. #endif
  663. #ifndef OPENSSL_NO_TLS1_3
  664. {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
  665. #endif
  666. #ifndef OPENSSL_NO_DTLS
  667. {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
  668. {"timeout", OPT_TIMEOUT, '-',
  669. "Enable send/receive timeout on DTLS connections"},
  670. {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
  671. #endif
  672. #ifndef OPENSSL_NO_DTLS1
  673. {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
  674. #endif
  675. #ifndef OPENSSL_NO_DTLS1_2
  676. {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
  677. #endif
  678. #ifndef OPENSSL_NO_SCTP
  679. {"sctp", OPT_SCTP, '-', "Use SCTP"},
  680. {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
  681. #endif
  682. #ifndef OPENSSL_NO_SSL_TRACE
  683. {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
  684. #endif
  685. #ifdef WATT32
  686. {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
  687. #endif
  688. {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
  689. {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
  690. {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
  691. {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
  692. #ifndef OPENSSL_NO_SRP
  693. {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
  694. {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
  695. {"srp_lateuser", OPT_SRP_LATEUSER, '-',
  696. "SRP username into second ClientHello message"},
  697. {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
  698. "Tolerate other than the known g N values."},
  699. {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
  700. #endif
  701. #ifndef OPENSSL_NO_NEXTPROTONEG
  702. {"nextprotoneg", OPT_NEXTPROTONEG, 's',
  703. "Enable NPN extension, considering named protocols supported (comma-separated list)"},
  704. #endif
  705. #ifndef OPENSSL_NO_ENGINE
  706. {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
  707. {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
  708. "Specify engine to be used for client certificate operations"},
  709. #endif
  710. #ifndef OPENSSL_NO_CT
  711. {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
  712. {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
  713. {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
  714. #endif
  715. {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
  716. {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
  717. {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
  718. {NULL, OPT_EOF, 0x00, NULL}
  719. };
  720. typedef enum PROTOCOL_choice {
  721. PROTO_OFF,
  722. PROTO_SMTP,
  723. PROTO_POP3,
  724. PROTO_IMAP,
  725. PROTO_FTP,
  726. PROTO_TELNET,
  727. PROTO_XMPP,
  728. PROTO_XMPP_SERVER,
  729. PROTO_CONNECT,
  730. PROTO_IRC,
  731. PROTO_MYSQL,
  732. PROTO_POSTGRES,
  733. PROTO_LMTP,
  734. PROTO_NNTP,
  735. PROTO_SIEVE,
  736. PROTO_LDAP
  737. } PROTOCOL_CHOICE;
  738. static const OPT_PAIR services[] = {
  739. {"smtp", PROTO_SMTP},
  740. {"pop3", PROTO_POP3},
  741. {"imap", PROTO_IMAP},
  742. {"ftp", PROTO_FTP},
  743. {"xmpp", PROTO_XMPP},
  744. {"xmpp-server", PROTO_XMPP_SERVER},
  745. {"telnet", PROTO_TELNET},
  746. {"irc", PROTO_IRC},
  747. {"mysql", PROTO_MYSQL},
  748. {"postgres", PROTO_POSTGRES},
  749. {"lmtp", PROTO_LMTP},
  750. {"nntp", PROTO_NNTP},
  751. {"sieve", PROTO_SIEVE},
  752. {"ldap", PROTO_LDAP},
  753. {NULL, 0}
  754. };
  755. #define IS_INET_FLAG(o) \
  756. (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
  757. #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
  758. #define IS_PROT_FLAG(o) \
  759. (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
  760. || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
  761. /* Free |*dest| and optionally set it to a copy of |source|. */
  762. static void freeandcopy(char **dest, const char *source)
  763. {
  764. OPENSSL_free(*dest);
  765. *dest = NULL;
  766. if (source != NULL)
  767. *dest = OPENSSL_strdup(source);
  768. }
  769. static int new_session_cb(SSL *s, SSL_SESSION *sess)
  770. {
  771. if (sess_out != NULL) {
  772. BIO *stmp = BIO_new_file(sess_out, "w");
  773. if (stmp == NULL) {
  774. BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
  775. } else {
  776. PEM_write_bio_SSL_SESSION(stmp, sess);
  777. BIO_free(stmp);
  778. }
  779. }
  780. /*
  781. * Session data gets dumped on connection for TLSv1.2 and below, and on
  782. * arrival of the NewSessionTicket for TLSv1.3.
  783. */
  784. if (SSL_version(s) == TLS1_3_VERSION) {
  785. BIO_printf(bio_c_out,
  786. "---\nPost-Handshake New Session Ticket arrived:\n");
  787. SSL_SESSION_print(bio_c_out, sess);
  788. BIO_printf(bio_c_out, "---\n");
  789. }
  790. /*
  791. * We always return a "fail" response so that the session gets freed again
  792. * because we haven't used the reference.
  793. */
  794. return 0;
  795. }
  796. int s_client_main(int argc, char **argv)
  797. {
  798. BIO *sbio;
  799. EVP_PKEY *key = NULL;
  800. SSL *con = NULL;
  801. SSL_CTX *ctx = NULL;
  802. STACK_OF(X509) *chain = NULL;
  803. X509 *cert = NULL;
  804. X509_VERIFY_PARAM *vpm = NULL;
  805. SSL_EXCERT *exc = NULL;
  806. SSL_CONF_CTX *cctx = NULL;
  807. STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
  808. char *dane_tlsa_domain = NULL;
  809. STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
  810. int dane_ee_no_name = 0;
  811. STACK_OF(X509_CRL) *crls = NULL;
  812. const SSL_METHOD *meth = TLS_client_method();
  813. const char *CApath = NULL, *CAfile = NULL;
  814. char *cbuf = NULL, *sbuf = NULL;
  815. char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL, *bindstr = NULL;
  816. char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
  817. char *chCApath = NULL, *chCAfile = NULL, *host = NULL;
  818. char *port = OPENSSL_strdup(PORT);
  819. char *bindhost = NULL, *bindport = NULL;
  820. char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
  821. char *ReqCAfile = NULL;
  822. char *sess_in = NULL, *crl_file = NULL, *p;
  823. const char *protohost = NULL;
  824. struct timeval timeout, *timeoutp;
  825. fd_set readfds, writefds;
  826. int noCApath = 0, noCAfile = 0;
  827. int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
  828. int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
  829. int prexit = 0;
  830. int sdebug = 0;
  831. int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
  832. int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0;
  833. int sbuf_len, sbuf_off, cmdletters = 1;
  834. int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
  835. int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
  836. int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
  837. #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
  838. int at_eof = 0;
  839. #endif
  840. int read_buf_len = 0;
  841. int fallback_scsv = 0;
  842. OPTION_CHOICE o;
  843. #ifndef OPENSSL_NO_DTLS
  844. int enable_timeouts = 0;
  845. long socket_mtu = 0;
  846. #endif
  847. #ifndef OPENSSL_NO_ENGINE
  848. ENGINE *ssl_client_engine = NULL;
  849. #endif
  850. ENGINE *e = NULL;
  851. #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
  852. struct timeval tv;
  853. #endif
  854. const char *servername = NULL;
  855. int noservername = 0;
  856. const char *alpn_in = NULL;
  857. tlsextctx tlsextcbp = { NULL, 0 };
  858. const char *ssl_config = NULL;
  859. #define MAX_SI_TYPES 100
  860. unsigned short serverinfo_types[MAX_SI_TYPES];
  861. int serverinfo_count = 0, start = 0, len;
  862. #ifndef OPENSSL_NO_NEXTPROTONEG
  863. const char *next_proto_neg_in = NULL;
  864. #endif
  865. #ifndef OPENSSL_NO_SRP
  866. char *srppass = NULL;
  867. int srp_lateuser = 0;
  868. SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
  869. #endif
  870. #ifndef OPENSSL_NO_SRTP
  871. char *srtp_profiles = NULL;
  872. #endif
  873. #ifndef OPENSSL_NO_CT
  874. char *ctlog_file = NULL;
  875. int ct_validation = 0;
  876. #endif
  877. int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
  878. int async = 0;
  879. unsigned int max_send_fragment = 0;
  880. unsigned int split_send_fragment = 0, max_pipelines = 0;
  881. enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
  882. int count4or6 = 0;
  883. uint8_t maxfraglen = 0;
  884. int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
  885. int c_tlsextdebug = 0;
  886. #ifndef OPENSSL_NO_OCSP
  887. int c_status_req = 0;
  888. #endif
  889. BIO *bio_c_msg = NULL;
  890. const char *keylog_file = NULL, *early_data_file = NULL;
  891. #ifndef OPENSSL_NO_DTLS
  892. int isdtls = 0;
  893. #endif
  894. char *psksessf = NULL;
  895. int enable_pha = 0;
  896. #ifndef OPENSSL_NO_SCTP
  897. int sctp_label_bug = 0;
  898. #endif
  899. FD_ZERO(&readfds);
  900. FD_ZERO(&writefds);
  901. /* Known false-positive of MemorySanitizer. */
  902. #if defined(__has_feature)
  903. # if __has_feature(memory_sanitizer)
  904. __msan_unpoison(&readfds, sizeof(readfds));
  905. __msan_unpoison(&writefds, sizeof(writefds));
  906. # endif
  907. #endif
  908. prog = opt_progname(argv[0]);
  909. c_quiet = 0;
  910. c_debug = 0;
  911. c_showcerts = 0;
  912. c_nbio = 0;
  913. vpm = X509_VERIFY_PARAM_new();
  914. cctx = SSL_CONF_CTX_new();
  915. if (vpm == NULL || cctx == NULL) {
  916. BIO_printf(bio_err, "%s: out of memory\n", prog);
  917. goto end;
  918. }
  919. cbuf = app_malloc(BUFSIZZ, "cbuf");
  920. sbuf = app_malloc(BUFSIZZ, "sbuf");
  921. mbuf = app_malloc(BUFSIZZ, "mbuf");
  922. SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
  923. prog = opt_init(argc, argv, s_client_options);
  924. while ((o = opt_next()) != OPT_EOF) {
  925. /* Check for intermixing flags. */
  926. if (connect_type == use_unix && IS_INET_FLAG(o)) {
  927. BIO_printf(bio_err,
  928. "%s: Intermixed protocol flags (unix and internet domains)\n",
  929. prog);
  930. goto end;
  931. }
  932. if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
  933. BIO_printf(bio_err,
  934. "%s: Intermixed protocol flags (internet and unix domains)\n",
  935. prog);
  936. goto end;
  937. }
  938. if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
  939. BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
  940. goto end;
  941. }
  942. if (IS_NO_PROT_FLAG(o))
  943. no_prot_opt++;
  944. if (prot_opt == 1 && no_prot_opt) {
  945. BIO_printf(bio_err,
  946. "Cannot supply both a protocol flag and '-no_<prot>'\n");
  947. goto end;
  948. }
  949. switch (o) {
  950. case OPT_EOF:
  951. case OPT_ERR:
  952. opthelp:
  953. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  954. goto end;
  955. case OPT_HELP:
  956. opt_help(s_client_options);
  957. ret = 0;
  958. goto end;
  959. case OPT_4:
  960. connect_type = use_inet;
  961. socket_family = AF_INET;
  962. count4or6++;
  963. break;
  964. #ifdef AF_INET6
  965. case OPT_6:
  966. connect_type = use_inet;
  967. socket_family = AF_INET6;
  968. count4or6++;
  969. break;
  970. #endif
  971. case OPT_HOST:
  972. connect_type = use_inet;
  973. freeandcopy(&host, opt_arg());
  974. break;
  975. case OPT_PORT:
  976. connect_type = use_inet;
  977. freeandcopy(&port, opt_arg());
  978. break;
  979. case OPT_CONNECT:
  980. connect_type = use_inet;
  981. freeandcopy(&connectstr, opt_arg());
  982. break;
  983. case OPT_BIND:
  984. freeandcopy(&bindstr, opt_arg());
  985. break;
  986. case OPT_PROXY:
  987. proxystr = opt_arg();
  988. starttls_proto = PROTO_CONNECT;
  989. break;
  990. #ifdef AF_UNIX
  991. case OPT_UNIX:
  992. connect_type = use_unix;
  993. socket_family = AF_UNIX;
  994. freeandcopy(&host, opt_arg());
  995. break;
  996. #endif
  997. case OPT_XMPPHOST:
  998. /* fall through, since this is an alias */
  999. case OPT_PROTOHOST:
  1000. protohost = opt_arg();
  1001. break;
  1002. case OPT_VERIFY:
  1003. verify = SSL_VERIFY_PEER;
  1004. verify_args.depth = atoi(opt_arg());
  1005. if (!c_quiet)
  1006. BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
  1007. break;
  1008. case OPT_CERT:
  1009. cert_file = opt_arg();
  1010. break;
  1011. case OPT_NAMEOPT:
  1012. if (!set_nameopt(opt_arg()))
  1013. goto end;
  1014. break;
  1015. case OPT_CRL:
  1016. crl_file = opt_arg();
  1017. break;
  1018. case OPT_CRL_DOWNLOAD:
  1019. crl_download = 1;
  1020. break;
  1021. case OPT_SESS_OUT:
  1022. sess_out = opt_arg();
  1023. break;
  1024. case OPT_SESS_IN:
  1025. sess_in = opt_arg();
  1026. break;
  1027. case OPT_CERTFORM:
  1028. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
  1029. goto opthelp;
  1030. break;
  1031. case OPT_CRLFORM:
  1032. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
  1033. goto opthelp;
  1034. break;
  1035. case OPT_VERIFY_RET_ERROR:
  1036. verify = SSL_VERIFY_PEER;
  1037. verify_args.return_error = 1;
  1038. break;
  1039. case OPT_VERIFY_QUIET:
  1040. verify_args.quiet = 1;
  1041. break;
  1042. case OPT_BRIEF:
  1043. c_brief = verify_args.quiet = c_quiet = 1;
  1044. break;
  1045. case OPT_S_CASES:
  1046. if (ssl_args == NULL)
  1047. ssl_args = sk_OPENSSL_STRING_new_null();
  1048. if (ssl_args == NULL
  1049. || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
  1050. || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
  1051. BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
  1052. goto end;
  1053. }
  1054. break;
  1055. case OPT_V_CASES:
  1056. if (!opt_verify(o, vpm))
  1057. goto end;
  1058. vpmtouched++;
  1059. break;
  1060. case OPT_X_CASES:
  1061. if (!args_excert(o, &exc))
  1062. goto end;
  1063. break;
  1064. case OPT_PREXIT:
  1065. prexit = 1;
  1066. break;
  1067. case OPT_CRLF:
  1068. crlf = 1;
  1069. break;
  1070. case OPT_QUIET:
  1071. c_quiet = c_ign_eof = 1;
  1072. break;
  1073. case OPT_NBIO:
  1074. c_nbio = 1;
  1075. break;
  1076. case OPT_NOCMDS:
  1077. cmdletters = 0;
  1078. break;
  1079. case OPT_ENGINE:
  1080. e = setup_engine(opt_arg(), 1);
  1081. break;
  1082. case OPT_SSL_CLIENT_ENGINE:
  1083. #ifndef OPENSSL_NO_ENGINE
  1084. ssl_client_engine = ENGINE_by_id(opt_arg());
  1085. if (ssl_client_engine == NULL) {
  1086. BIO_printf(bio_err, "Error getting client auth engine\n");
  1087. goto opthelp;
  1088. }
  1089. #endif
  1090. break;
  1091. case OPT_R_CASES:
  1092. if (!opt_rand(o))
  1093. goto end;
  1094. break;
  1095. case OPT_IGN_EOF:
  1096. c_ign_eof = 1;
  1097. break;
  1098. case OPT_NO_IGN_EOF:
  1099. c_ign_eof = 0;
  1100. break;
  1101. case OPT_DEBUG:
  1102. c_debug = 1;
  1103. break;
  1104. case OPT_TLSEXTDEBUG:
  1105. c_tlsextdebug = 1;
  1106. break;
  1107. case OPT_STATUS:
  1108. #ifndef OPENSSL_NO_OCSP
  1109. c_status_req = 1;
  1110. #endif
  1111. break;
  1112. case OPT_WDEBUG:
  1113. #ifdef WATT32
  1114. dbug_init();
  1115. #endif
  1116. break;
  1117. case OPT_MSG:
  1118. c_msg = 1;
  1119. break;
  1120. case OPT_MSGFILE:
  1121. bio_c_msg = BIO_new_file(opt_arg(), "w");
  1122. break;
  1123. case OPT_TRACE:
  1124. #ifndef OPENSSL_NO_SSL_TRACE
  1125. c_msg = 2;
  1126. #endif
  1127. break;
  1128. case OPT_SECURITY_DEBUG:
  1129. sdebug = 1;
  1130. break;
  1131. case OPT_SECURITY_DEBUG_VERBOSE:
  1132. sdebug = 2;
  1133. break;
  1134. case OPT_SHOWCERTS:
  1135. c_showcerts = 1;
  1136. break;
  1137. case OPT_NBIO_TEST:
  1138. nbio_test = 1;
  1139. break;
  1140. case OPT_STATE:
  1141. state = 1;
  1142. break;
  1143. case OPT_PSK_IDENTITY:
  1144. psk_identity = opt_arg();
  1145. break;
  1146. case OPT_PSK:
  1147. for (p = psk_key = opt_arg(); *p; p++) {
  1148. if (isxdigit(_UC(*p)))
  1149. continue;
  1150. BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
  1151. goto end;
  1152. }
  1153. break;
  1154. case OPT_PSK_SESS:
  1155. psksessf = opt_arg();
  1156. break;
  1157. #ifndef OPENSSL_NO_SRP
  1158. case OPT_SRPUSER:
  1159. srp_arg.srplogin = opt_arg();
  1160. if (min_version < TLS1_VERSION)
  1161. min_version = TLS1_VERSION;
  1162. break;
  1163. case OPT_SRPPASS:
  1164. srppass = opt_arg();
  1165. if (min_version < TLS1_VERSION)
  1166. min_version = TLS1_VERSION;
  1167. break;
  1168. case OPT_SRP_STRENGTH:
  1169. srp_arg.strength = atoi(opt_arg());
  1170. BIO_printf(bio_err, "SRP minimal length for N is %d\n",
  1171. srp_arg.strength);
  1172. if (min_version < TLS1_VERSION)
  1173. min_version = TLS1_VERSION;
  1174. break;
  1175. case OPT_SRP_LATEUSER:
  1176. srp_lateuser = 1;
  1177. if (min_version < TLS1_VERSION)
  1178. min_version = TLS1_VERSION;
  1179. break;
  1180. case OPT_SRP_MOREGROUPS:
  1181. srp_arg.amp = 1;
  1182. if (min_version < TLS1_VERSION)
  1183. min_version = TLS1_VERSION;
  1184. break;
  1185. #endif
  1186. case OPT_SSL_CONFIG:
  1187. ssl_config = opt_arg();
  1188. break;
  1189. case OPT_SSL3:
  1190. min_version = SSL3_VERSION;
  1191. max_version = SSL3_VERSION;
  1192. socket_type = SOCK_STREAM;
  1193. #ifndef OPENSSL_NO_DTLS
  1194. isdtls = 0;
  1195. #endif
  1196. break;
  1197. case OPT_TLS1_3:
  1198. min_version = TLS1_3_VERSION;
  1199. max_version = TLS1_3_VERSION;
  1200. socket_type = SOCK_STREAM;
  1201. #ifndef OPENSSL_NO_DTLS
  1202. isdtls = 0;
  1203. #endif
  1204. break;
  1205. case OPT_TLS1_2:
  1206. min_version = TLS1_2_VERSION;
  1207. max_version = TLS1_2_VERSION;
  1208. socket_type = SOCK_STREAM;
  1209. #ifndef OPENSSL_NO_DTLS
  1210. isdtls = 0;
  1211. #endif
  1212. break;
  1213. case OPT_TLS1_1:
  1214. min_version = TLS1_1_VERSION;
  1215. max_version = TLS1_1_VERSION;
  1216. socket_type = SOCK_STREAM;
  1217. #ifndef OPENSSL_NO_DTLS
  1218. isdtls = 0;
  1219. #endif
  1220. break;
  1221. case OPT_TLS1:
  1222. min_version = TLS1_VERSION;
  1223. max_version = TLS1_VERSION;
  1224. socket_type = SOCK_STREAM;
  1225. #ifndef OPENSSL_NO_DTLS
  1226. isdtls = 0;
  1227. #endif
  1228. break;
  1229. case OPT_DTLS:
  1230. #ifndef OPENSSL_NO_DTLS
  1231. meth = DTLS_client_method();
  1232. socket_type = SOCK_DGRAM;
  1233. isdtls = 1;
  1234. #endif
  1235. break;
  1236. case OPT_DTLS1:
  1237. #ifndef OPENSSL_NO_DTLS1
  1238. meth = DTLS_client_method();
  1239. min_version = DTLS1_VERSION;
  1240. max_version = DTLS1_VERSION;
  1241. socket_type = SOCK_DGRAM;
  1242. isdtls = 1;
  1243. #endif
  1244. break;
  1245. case OPT_DTLS1_2:
  1246. #ifndef OPENSSL_NO_DTLS1_2
  1247. meth = DTLS_client_method();
  1248. min_version = DTLS1_2_VERSION;
  1249. max_version = DTLS1_2_VERSION;
  1250. socket_type = SOCK_DGRAM;
  1251. isdtls = 1;
  1252. #endif
  1253. break;
  1254. case OPT_SCTP:
  1255. #ifndef OPENSSL_NO_SCTP
  1256. protocol = IPPROTO_SCTP;
  1257. #endif
  1258. break;
  1259. case OPT_SCTP_LABEL_BUG:
  1260. #ifndef OPENSSL_NO_SCTP
  1261. sctp_label_bug = 1;
  1262. #endif
  1263. break;
  1264. case OPT_TIMEOUT:
  1265. #ifndef OPENSSL_NO_DTLS
  1266. enable_timeouts = 1;
  1267. #endif
  1268. break;
  1269. case OPT_MTU:
  1270. #ifndef OPENSSL_NO_DTLS
  1271. socket_mtu = atol(opt_arg());
  1272. #endif
  1273. break;
  1274. case OPT_FALLBACKSCSV:
  1275. fallback_scsv = 1;
  1276. break;
  1277. case OPT_KEYFORM:
  1278. if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
  1279. goto opthelp;
  1280. break;
  1281. case OPT_PASS:
  1282. passarg = opt_arg();
  1283. break;
  1284. case OPT_CERT_CHAIN:
  1285. chain_file = opt_arg();
  1286. break;
  1287. case OPT_KEY:
  1288. key_file = opt_arg();
  1289. break;
  1290. case OPT_RECONNECT:
  1291. reconnect = 5;
  1292. break;
  1293. case OPT_CAPATH:
  1294. CApath = opt_arg();
  1295. break;
  1296. case OPT_NOCAPATH:
  1297. noCApath = 1;
  1298. break;
  1299. case OPT_CHAINCAPATH:
  1300. chCApath = opt_arg();
  1301. break;
  1302. case OPT_VERIFYCAPATH:
  1303. vfyCApath = opt_arg();
  1304. break;
  1305. case OPT_BUILD_CHAIN:
  1306. build_chain = 1;
  1307. break;
  1308. case OPT_REQCAFILE:
  1309. ReqCAfile = opt_arg();
  1310. break;
  1311. case OPT_CAFILE:
  1312. CAfile = opt_arg();
  1313. break;
  1314. case OPT_NOCAFILE:
  1315. noCAfile = 1;
  1316. break;
  1317. #ifndef OPENSSL_NO_CT
  1318. case OPT_NOCT:
  1319. ct_validation = 0;
  1320. break;
  1321. case OPT_CT:
  1322. ct_validation = 1;
  1323. break;
  1324. case OPT_CTLOG_FILE:
  1325. ctlog_file = opt_arg();
  1326. break;
  1327. #endif
  1328. case OPT_CHAINCAFILE:
  1329. chCAfile = opt_arg();
  1330. break;
  1331. case OPT_VERIFYCAFILE:
  1332. vfyCAfile = opt_arg();
  1333. break;
  1334. case OPT_DANE_TLSA_DOMAIN:
  1335. dane_tlsa_domain = opt_arg();
  1336. break;
  1337. case OPT_DANE_TLSA_RRDATA:
  1338. if (dane_tlsa_rrset == NULL)
  1339. dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
  1340. if (dane_tlsa_rrset == NULL ||
  1341. !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
  1342. BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
  1343. goto end;
  1344. }
  1345. break;
  1346. case OPT_DANE_EE_NO_NAME:
  1347. dane_ee_no_name = 1;
  1348. break;
  1349. case OPT_NEXTPROTONEG:
  1350. #ifndef OPENSSL_NO_NEXTPROTONEG
  1351. next_proto_neg_in = opt_arg();
  1352. #endif
  1353. break;
  1354. case OPT_ALPN:
  1355. alpn_in = opt_arg();
  1356. break;
  1357. case OPT_SERVERINFO:
  1358. p = opt_arg();
  1359. len = strlen(p);
  1360. for (start = 0, i = 0; i <= len; ++i) {
  1361. if (i == len || p[i] == ',') {
  1362. serverinfo_types[serverinfo_count] = atoi(p + start);
  1363. if (++serverinfo_count == MAX_SI_TYPES)
  1364. break;
  1365. start = i + 1;
  1366. }
  1367. }
  1368. break;
  1369. case OPT_STARTTLS:
  1370. if (!opt_pair(opt_arg(), services, &starttls_proto))
  1371. goto end;
  1372. break;
  1373. case OPT_SERVERNAME:
  1374. servername = opt_arg();
  1375. break;
  1376. case OPT_NOSERVERNAME:
  1377. noservername = 1;
  1378. break;
  1379. case OPT_USE_SRTP:
  1380. #ifndef OPENSSL_NO_SRTP
  1381. srtp_profiles = opt_arg();
  1382. #endif
  1383. break;
  1384. case OPT_KEYMATEXPORT:
  1385. keymatexportlabel = opt_arg();
  1386. break;
  1387. case OPT_KEYMATEXPORTLEN:
  1388. keymatexportlen = atoi(opt_arg());
  1389. break;
  1390. case OPT_ASYNC:
  1391. async = 1;
  1392. break;
  1393. case OPT_MAXFRAGLEN:
  1394. len = atoi(opt_arg());
  1395. switch (len) {
  1396. case 512:
  1397. maxfraglen = TLSEXT_max_fragment_length_512;
  1398. break;
  1399. case 1024:
  1400. maxfraglen = TLSEXT_max_fragment_length_1024;
  1401. break;
  1402. case 2048:
  1403. maxfraglen = TLSEXT_max_fragment_length_2048;
  1404. break;
  1405. case 4096:
  1406. maxfraglen = TLSEXT_max_fragment_length_4096;
  1407. break;
  1408. default:
  1409. BIO_printf(bio_err,
  1410. "%s: Max Fragment Len %u is out of permitted values",
  1411. prog, len);
  1412. goto opthelp;
  1413. }
  1414. break;
  1415. case OPT_MAX_SEND_FRAG:
  1416. max_send_fragment = atoi(opt_arg());
  1417. break;
  1418. case OPT_SPLIT_SEND_FRAG:
  1419. split_send_fragment = atoi(opt_arg());
  1420. break;
  1421. case OPT_MAX_PIPELINES:
  1422. max_pipelines = atoi(opt_arg());
  1423. break;
  1424. case OPT_READ_BUF:
  1425. read_buf_len = atoi(opt_arg());
  1426. break;
  1427. case OPT_KEYLOG_FILE:
  1428. keylog_file = opt_arg();
  1429. break;
  1430. case OPT_EARLY_DATA:
  1431. early_data_file = opt_arg();
  1432. break;
  1433. case OPT_ENABLE_PHA:
  1434. enable_pha = 1;
  1435. break;
  1436. }
  1437. }
  1438. if (count4or6 >= 2) {
  1439. BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
  1440. goto opthelp;
  1441. }
  1442. if (noservername) {
  1443. if (servername != NULL) {
  1444. BIO_printf(bio_err,
  1445. "%s: Can't use -servername and -noservername together\n",
  1446. prog);
  1447. goto opthelp;
  1448. }
  1449. if (dane_tlsa_domain != NULL) {
  1450. BIO_printf(bio_err,
  1451. "%s: Can't use -dane_tlsa_domain and -noservername together\n",
  1452. prog);
  1453. goto opthelp;
  1454. }
  1455. }
  1456. argc = opt_num_rest();
  1457. if (argc == 1) {
  1458. /* If there's a positional argument, it's the equivalent of
  1459. * OPT_CONNECT.
  1460. * Don't allow -connect and a separate argument.
  1461. */
  1462. if (connectstr != NULL) {
  1463. BIO_printf(bio_err,
  1464. "%s: must not provide both -connect option and target parameter\n",
  1465. prog);
  1466. goto opthelp;
  1467. }
  1468. connect_type = use_inet;
  1469. freeandcopy(&connectstr, *opt_rest());
  1470. } else if (argc != 0) {
  1471. goto opthelp;
  1472. }
  1473. #ifndef OPENSSL_NO_NEXTPROTONEG
  1474. if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
  1475. BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
  1476. goto opthelp;
  1477. }
  1478. #endif
  1479. if (proxystr != NULL) {
  1480. int res;
  1481. char *tmp_host = host, *tmp_port = port;
  1482. if (connectstr == NULL) {
  1483. BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
  1484. goto opthelp;
  1485. }
  1486. res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
  1487. if (tmp_host != host)
  1488. OPENSSL_free(tmp_host);
  1489. if (tmp_port != port)
  1490. OPENSSL_free(tmp_port);
  1491. if (!res) {
  1492. BIO_printf(bio_err,
  1493. "%s: -proxy argument malformed or ambiguous\n", prog);
  1494. goto end;
  1495. }
  1496. } else {
  1497. int res = 1;
  1498. char *tmp_host = host, *tmp_port = port;
  1499. if (connectstr != NULL)
  1500. res = BIO_parse_hostserv(connectstr, &host, &port,
  1501. BIO_PARSE_PRIO_HOST);
  1502. if (tmp_host != host)
  1503. OPENSSL_free(tmp_host);
  1504. if (tmp_port != port)
  1505. OPENSSL_free(tmp_port);
  1506. if (!res) {
  1507. BIO_printf(bio_err,
  1508. "%s: -connect argument or target parameter malformed or ambiguous\n",
  1509. prog);
  1510. goto end;
  1511. }
  1512. }
  1513. if (bindstr != NULL) {
  1514. int res;
  1515. res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
  1516. BIO_PARSE_PRIO_HOST);
  1517. if (!res) {
  1518. BIO_printf(bio_err,
  1519. "%s: -bind argument parameter malformed or ambiguous\n",
  1520. prog);
  1521. goto end;
  1522. }
  1523. }
  1524. #ifdef AF_UNIX
  1525. if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
  1526. BIO_printf(bio_err,
  1527. "Can't use unix sockets and datagrams together\n");
  1528. goto end;
  1529. }
  1530. #endif
  1531. #ifndef OPENSSL_NO_SCTP
  1532. if (protocol == IPPROTO_SCTP) {
  1533. if (socket_type != SOCK_DGRAM) {
  1534. BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
  1535. goto end;
  1536. }
  1537. /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
  1538. socket_type = SOCK_STREAM;
  1539. }
  1540. #endif
  1541. #if !defined(OPENSSL_NO_NEXTPROTONEG)
  1542. next_proto.status = -1;
  1543. if (next_proto_neg_in) {
  1544. next_proto.data =
  1545. next_protos_parse(&next_proto.len, next_proto_neg_in);
  1546. if (next_proto.data == NULL) {
  1547. BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
  1548. goto end;
  1549. }
  1550. } else
  1551. next_proto.data = NULL;
  1552. #endif
  1553. if (!app_passwd(passarg, NULL, &pass, NULL)) {
  1554. BIO_printf(bio_err, "Error getting password\n");
  1555. goto end;
  1556. }
  1557. if (key_file == NULL)
  1558. key_file = cert_file;
  1559. if (key_file != NULL) {
  1560. key = load_key(key_file, key_format, 0, pass, e,
  1561. "client certificate private key file");
  1562. if (key == NULL) {
  1563. ERR_print_errors(bio_err);
  1564. goto end;
  1565. }
  1566. }
  1567. if (cert_file != NULL) {
  1568. cert = load_cert(cert_file, cert_format, "client certificate file");
  1569. if (cert == NULL) {
  1570. ERR_print_errors(bio_err);
  1571. goto end;
  1572. }
  1573. }
  1574. if (chain_file != NULL) {
  1575. if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
  1576. "client certificate chain"))
  1577. goto end;
  1578. }
  1579. if (crl_file != NULL) {
  1580. X509_CRL *crl;
  1581. crl = load_crl(crl_file, crl_format);
  1582. if (crl == NULL) {
  1583. BIO_puts(bio_err, "Error loading CRL\n");
  1584. ERR_print_errors(bio_err);
  1585. goto end;
  1586. }
  1587. crls = sk_X509_CRL_new_null();
  1588. if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
  1589. BIO_puts(bio_err, "Error adding CRL\n");
  1590. ERR_print_errors(bio_err);
  1591. X509_CRL_free(crl);
  1592. goto end;
  1593. }
  1594. }
  1595. if (!load_excert(&exc))
  1596. goto end;
  1597. if (bio_c_out == NULL) {
  1598. if (c_quiet && !c_debug) {
  1599. bio_c_out = BIO_new(BIO_s_null());
  1600. if (c_msg && bio_c_msg == NULL)
  1601. bio_c_msg = dup_bio_out(FORMAT_TEXT);
  1602. } else if (bio_c_out == NULL)
  1603. bio_c_out = dup_bio_out(FORMAT_TEXT);
  1604. }
  1605. #ifndef OPENSSL_NO_SRP
  1606. if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
  1607. BIO_printf(bio_err, "Error getting password\n");
  1608. goto end;
  1609. }
  1610. #endif
  1611. ctx = SSL_CTX_new(meth);
  1612. if (ctx == NULL) {
  1613. ERR_print_errors(bio_err);
  1614. goto end;
  1615. }
  1616. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  1617. if (sdebug)
  1618. ssl_ctx_security_debug(ctx, sdebug);
  1619. if (!config_ctx(cctx, ssl_args, ctx))
  1620. goto end;
  1621. if (ssl_config != NULL) {
  1622. if (SSL_CTX_config(ctx, ssl_config) == 0) {
  1623. BIO_printf(bio_err, "Error using configuration \"%s\"\n",
  1624. ssl_config);
  1625. ERR_print_errors(bio_err);
  1626. goto end;
  1627. }
  1628. }
  1629. #ifndef OPENSSL_NO_SCTP
  1630. if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
  1631. SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
  1632. #endif
  1633. if (min_version != 0
  1634. && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
  1635. goto end;
  1636. if (max_version != 0
  1637. && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
  1638. goto end;
  1639. if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
  1640. BIO_printf(bio_err, "Error setting verify params\n");
  1641. ERR_print_errors(bio_err);
  1642. goto end;
  1643. }
  1644. if (async) {
  1645. SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
  1646. }
  1647. if (max_send_fragment > 0
  1648. && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
  1649. BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
  1650. prog, max_send_fragment);
  1651. goto end;
  1652. }
  1653. if (split_send_fragment > 0
  1654. && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
  1655. BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
  1656. prog, split_send_fragment);
  1657. goto end;
  1658. }
  1659. if (max_pipelines > 0
  1660. && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
  1661. BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
  1662. prog, max_pipelines);
  1663. goto end;
  1664. }
  1665. if (read_buf_len > 0) {
  1666. SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
  1667. }
  1668. if (maxfraglen > 0
  1669. && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
  1670. BIO_printf(bio_err,
  1671. "%s: Max Fragment Length code %u is out of permitted values"
  1672. "\n", prog, maxfraglen);
  1673. goto end;
  1674. }
  1675. if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
  1676. crls, crl_download)) {
  1677. BIO_printf(bio_err, "Error loading store locations\n");
  1678. ERR_print_errors(bio_err);
  1679. goto end;
  1680. }
  1681. if (ReqCAfile != NULL) {
  1682. STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
  1683. if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
  1684. sk_X509_NAME_pop_free(nm, X509_NAME_free);
  1685. BIO_printf(bio_err, "Error loading CA names\n");
  1686. ERR_print_errors(bio_err);
  1687. goto end;
  1688. }
  1689. SSL_CTX_set0_CA_list(ctx, nm);
  1690. }
  1691. #ifndef OPENSSL_NO_ENGINE
  1692. if (ssl_client_engine) {
  1693. if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
  1694. BIO_puts(bio_err, "Error setting client auth engine\n");
  1695. ERR_print_errors(bio_err);
  1696. ENGINE_free(ssl_client_engine);
  1697. goto end;
  1698. }
  1699. ENGINE_free(ssl_client_engine);
  1700. }
  1701. #endif
  1702. #ifndef OPENSSL_NO_PSK
  1703. if (psk_key != NULL) {
  1704. if (c_debug)
  1705. BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
  1706. SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
  1707. }
  1708. #endif
  1709. if (psksessf != NULL) {
  1710. BIO *stmp = BIO_new_file(psksessf, "r");
  1711. if (stmp == NULL) {
  1712. BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
  1713. ERR_print_errors(bio_err);
  1714. goto end;
  1715. }
  1716. psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
  1717. BIO_free(stmp);
  1718. if (psksess == NULL) {
  1719. BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
  1720. ERR_print_errors(bio_err);
  1721. goto end;
  1722. }
  1723. }
  1724. if (psk_key != NULL || psksess != NULL)
  1725. SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
  1726. #ifndef OPENSSL_NO_SRTP
  1727. if (srtp_profiles != NULL) {
  1728. /* Returns 0 on success! */
  1729. if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
  1730. BIO_printf(bio_err, "Error setting SRTP profile\n");
  1731. ERR_print_errors(bio_err);
  1732. goto end;
  1733. }
  1734. }
  1735. #endif
  1736. if (exc != NULL)
  1737. ssl_ctx_set_excert(ctx, exc);
  1738. #if !defined(OPENSSL_NO_NEXTPROTONEG)
  1739. if (next_proto.data != NULL)
  1740. SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
  1741. #endif
  1742. if (alpn_in) {
  1743. size_t alpn_len;
  1744. unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
  1745. if (alpn == NULL) {
  1746. BIO_printf(bio_err, "Error parsing -alpn argument\n");
  1747. goto end;
  1748. }
  1749. /* Returns 0 on success! */
  1750. if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
  1751. BIO_printf(bio_err, "Error setting ALPN\n");
  1752. goto end;
  1753. }
  1754. OPENSSL_free(alpn);
  1755. }
  1756. for (i = 0; i < serverinfo_count; i++) {
  1757. if (!SSL_CTX_add_client_custom_ext(ctx,
  1758. serverinfo_types[i],
  1759. NULL, NULL, NULL,
  1760. serverinfo_cli_parse_cb, NULL)) {
  1761. BIO_printf(bio_err,
  1762. "Warning: Unable to add custom extension %u, skipping\n",
  1763. serverinfo_types[i]);
  1764. }
  1765. }
  1766. if (state)
  1767. SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
  1768. #ifndef OPENSSL_NO_CT
  1769. /* Enable SCT processing, without early connection termination */
  1770. if (ct_validation &&
  1771. !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
  1772. ERR_print_errors(bio_err);
  1773. goto end;
  1774. }
  1775. if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
  1776. if (ct_validation) {
  1777. ERR_print_errors(bio_err);
  1778. goto end;
  1779. }
  1780. /*
  1781. * If CT validation is not enabled, the log list isn't needed so don't
  1782. * show errors or abort. We try to load it regardless because then we
  1783. * can show the names of the logs any SCTs came from (SCTs may be seen
  1784. * even with validation disabled).
  1785. */
  1786. ERR_clear_error();
  1787. }
  1788. #endif
  1789. SSL_CTX_set_verify(ctx, verify, verify_callback);
  1790. if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
  1791. ERR_print_errors(bio_err);
  1792. goto end;
  1793. }
  1794. ssl_ctx_add_crls(ctx, crls, crl_download);
  1795. if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
  1796. goto end;
  1797. if (!noservername) {
  1798. tlsextcbp.biodebug = bio_err;
  1799. SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
  1800. SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
  1801. }
  1802. # ifndef OPENSSL_NO_SRP
  1803. if (srp_arg.srplogin) {
  1804. if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
  1805. BIO_printf(bio_err, "Unable to set SRP username\n");
  1806. goto end;
  1807. }
  1808. srp_arg.msg = c_msg;
  1809. srp_arg.debug = c_debug;
  1810. SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
  1811. SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
  1812. SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
  1813. if (c_msg || c_debug || srp_arg.amp == 0)
  1814. SSL_CTX_set_srp_verify_param_callback(ctx,
  1815. ssl_srp_verify_param_cb);
  1816. }
  1817. # endif
  1818. if (dane_tlsa_domain != NULL) {
  1819. if (SSL_CTX_dane_enable(ctx) <= 0) {
  1820. BIO_printf(bio_err,
  1821. "%s: Error enabling DANE TLSA authentication.\n",
  1822. prog);
  1823. ERR_print_errors(bio_err);
  1824. goto end;
  1825. }
  1826. }
  1827. /*
  1828. * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
  1829. * come at any time. Therefore we use a callback to write out the session
  1830. * when we know about it. This approach works for < TLSv1.3 as well.
  1831. */
  1832. SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
  1833. | SSL_SESS_CACHE_NO_INTERNAL_STORE);
  1834. SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
  1835. if (set_keylog_file(ctx, keylog_file))
  1836. goto end;
  1837. con = SSL_new(ctx);
  1838. if (con == NULL)
  1839. goto end;
  1840. if (enable_pha)
  1841. SSL_set_post_handshake_auth(con, 1);
  1842. if (sess_in != NULL) {
  1843. SSL_SESSION *sess;
  1844. BIO *stmp = BIO_new_file(sess_in, "r");
  1845. if (stmp == NULL) {
  1846. BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
  1847. ERR_print_errors(bio_err);
  1848. goto end;
  1849. }
  1850. sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
  1851. BIO_free(stmp);
  1852. if (sess == NULL) {
  1853. BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
  1854. ERR_print_errors(bio_err);
  1855. goto end;
  1856. }
  1857. if (!SSL_set_session(con, sess)) {
  1858. BIO_printf(bio_err, "Can't set session\n");
  1859. ERR_print_errors(bio_err);
  1860. goto end;
  1861. }
  1862. SSL_SESSION_free(sess);
  1863. }
  1864. if (fallback_scsv)
  1865. SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
  1866. if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
  1867. if (servername == NULL) {
  1868. if(host == NULL || is_dNS_name(host))
  1869. servername = (host == NULL) ? "localhost" : host;
  1870. }
  1871. if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
  1872. BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
  1873. ERR_print_errors(bio_err);
  1874. goto end;
  1875. }
  1876. }
  1877. if (dane_tlsa_domain != NULL) {
  1878. if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
  1879. BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
  1880. "authentication.\n", prog);
  1881. ERR_print_errors(bio_err);
  1882. goto end;
  1883. }
  1884. if (dane_tlsa_rrset == NULL) {
  1885. BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
  1886. "least one -dane_tlsa_rrdata option.\n", prog);
  1887. goto end;
  1888. }
  1889. if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
  1890. BIO_printf(bio_err, "%s: Failed to import any TLSA "
  1891. "records.\n", prog);
  1892. goto end;
  1893. }
  1894. if (dane_ee_no_name)
  1895. SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
  1896. } else if (dane_tlsa_rrset != NULL) {
  1897. BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
  1898. "-dane_tlsa_domain option.\n", prog);
  1899. goto end;
  1900. }
  1901. re_start:
  1902. if (init_client(&s, host, port, bindhost, bindport, socket_family,
  1903. socket_type, protocol) == 0) {
  1904. BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
  1905. BIO_closesocket(s);
  1906. goto end;
  1907. }
  1908. BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
  1909. if (c_nbio) {
  1910. if (!BIO_socket_nbio(s, 1)) {
  1911. ERR_print_errors(bio_err);
  1912. goto end;
  1913. }
  1914. BIO_printf(bio_c_out, "Turned on non blocking io\n");
  1915. }
  1916. #ifndef OPENSSL_NO_DTLS
  1917. if (isdtls) {
  1918. union BIO_sock_info_u peer_info;
  1919. #ifndef OPENSSL_NO_SCTP
  1920. if (protocol == IPPROTO_SCTP)
  1921. sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
  1922. else
  1923. #endif
  1924. sbio = BIO_new_dgram(s, BIO_NOCLOSE);
  1925. if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
  1926. BIO_printf(bio_err, "memory allocation failure\n");
  1927. BIO_closesocket(s);
  1928. goto end;
  1929. }
  1930. if (!BIO_sock_info(s, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
  1931. BIO_printf(bio_err, "getsockname:errno=%d\n",
  1932. get_last_socket_error());
  1933. BIO_ADDR_free(peer_info.addr);
  1934. BIO_closesocket(s);
  1935. goto end;
  1936. }
  1937. (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
  1938. BIO_ADDR_free(peer_info.addr);
  1939. peer_info.addr = NULL;
  1940. if (enable_timeouts) {
  1941. timeout.tv_sec = 0;
  1942. timeout.tv_usec = DGRAM_RCV_TIMEOUT;
  1943. BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
  1944. timeout.tv_sec = 0;
  1945. timeout.tv_usec = DGRAM_SND_TIMEOUT;
  1946. BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
  1947. }
  1948. if (socket_mtu) {
  1949. if (socket_mtu < DTLS_get_link_min_mtu(con)) {
  1950. BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
  1951. DTLS_get_link_min_mtu(con));
  1952. BIO_free(sbio);
  1953. goto shut;
  1954. }
  1955. SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
  1956. if (!DTLS_set_link_mtu(con, socket_mtu)) {
  1957. BIO_printf(bio_err, "Failed to set MTU\n");
  1958. BIO_free(sbio);
  1959. goto shut;
  1960. }
  1961. } else {
  1962. /* want to do MTU discovery */
  1963. BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
  1964. }
  1965. } else
  1966. #endif /* OPENSSL_NO_DTLS */
  1967. sbio = BIO_new_socket(s, BIO_NOCLOSE);
  1968. if (nbio_test) {
  1969. BIO *test;
  1970. test = BIO_new(BIO_f_nbio_test());
  1971. sbio = BIO_push(test, sbio);
  1972. }
  1973. if (c_debug) {
  1974. BIO_set_callback(sbio, bio_dump_callback);
  1975. BIO_set_callback_arg(sbio, (char *)bio_c_out);
  1976. }
  1977. if (c_msg) {
  1978. #ifndef OPENSSL_NO_SSL_TRACE
  1979. if (c_msg == 2)
  1980. SSL_set_msg_callback(con, SSL_trace);
  1981. else
  1982. #endif
  1983. SSL_set_msg_callback(con, msg_cb);
  1984. SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
  1985. }
  1986. if (c_tlsextdebug) {
  1987. SSL_set_tlsext_debug_callback(con, tlsext_cb);
  1988. SSL_set_tlsext_debug_arg(con, bio_c_out);
  1989. }
  1990. #ifndef OPENSSL_NO_OCSP
  1991. if (c_status_req) {
  1992. SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
  1993. SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
  1994. SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
  1995. }
  1996. #endif
  1997. SSL_set_bio(con, sbio, sbio);
  1998. SSL_set_connect_state(con);
  1999. /* ok, lets connect */
  2000. if (fileno_stdin() > SSL_get_fd(con))
  2001. width = fileno_stdin() + 1;
  2002. else
  2003. width = SSL_get_fd(con) + 1;
  2004. read_tty = 1;
  2005. write_tty = 0;
  2006. tty_on = 0;
  2007. read_ssl = 1;
  2008. write_ssl = 1;
  2009. cbuf_len = 0;
  2010. cbuf_off = 0;
  2011. sbuf_len = 0;
  2012. sbuf_off = 0;
  2013. switch ((PROTOCOL_CHOICE) starttls_proto) {
  2014. case PROTO_OFF:
  2015. break;
  2016. case PROTO_LMTP:
  2017. case PROTO_SMTP:
  2018. {
  2019. /*
  2020. * This is an ugly hack that does a lot of assumptions. We do
  2021. * have to handle multi-line responses which may come in a single
  2022. * packet or not. We therefore have to use BIO_gets() which does
  2023. * need a buffering BIO. So during the initial chitchat we do
  2024. * push a buffering BIO into the chain that is removed again
  2025. * later on to not disturb the rest of the s_client operation.
  2026. */
  2027. int foundit = 0;
  2028. BIO *fbio = BIO_new(BIO_f_buffer());
  2029. BIO_push(fbio, sbio);
  2030. /* Wait for multi-line response to end from LMTP or SMTP */
  2031. do {
  2032. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2033. } while (mbuf_len > 3 && mbuf[3] == '-');
  2034. if (protohost == NULL)
  2035. protohost = "mail.example.com";
  2036. if (starttls_proto == (int)PROTO_LMTP)
  2037. BIO_printf(fbio, "LHLO %s\r\n", protohost);
  2038. else
  2039. BIO_printf(fbio, "EHLO %s\r\n", protohost);
  2040. (void)BIO_flush(fbio);
  2041. /*
  2042. * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
  2043. * response.
  2044. */
  2045. do {
  2046. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2047. if (strstr(mbuf, "STARTTLS"))
  2048. foundit = 1;
  2049. } while (mbuf_len > 3 && mbuf[3] == '-');
  2050. (void)BIO_flush(fbio);
  2051. BIO_pop(fbio);
  2052. BIO_free(fbio);
  2053. if (!foundit)
  2054. BIO_printf(bio_err,
  2055. "Didn't find STARTTLS in server response,"
  2056. " trying anyway...\n");
  2057. BIO_printf(sbio, "STARTTLS\r\n");
  2058. BIO_read(sbio, sbuf, BUFSIZZ);
  2059. }
  2060. break;
  2061. case PROTO_POP3:
  2062. {
  2063. BIO_read(sbio, mbuf, BUFSIZZ);
  2064. BIO_printf(sbio, "STLS\r\n");
  2065. mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
  2066. if (mbuf_len < 0) {
  2067. BIO_printf(bio_err, "BIO_read failed\n");
  2068. goto end;
  2069. }
  2070. }
  2071. break;
  2072. case PROTO_IMAP:
  2073. {
  2074. int foundit = 0;
  2075. BIO *fbio = BIO_new(BIO_f_buffer());
  2076. BIO_push(fbio, sbio);
  2077. BIO_gets(fbio, mbuf, BUFSIZZ);
  2078. /* STARTTLS command requires CAPABILITY... */
  2079. BIO_printf(fbio, ". CAPABILITY\r\n");
  2080. (void)BIO_flush(fbio);
  2081. /* wait for multi-line CAPABILITY response */
  2082. do {
  2083. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2084. if (strstr(mbuf, "STARTTLS"))
  2085. foundit = 1;
  2086. }
  2087. while (mbuf_len > 3 && mbuf[0] != '.');
  2088. (void)BIO_flush(fbio);
  2089. BIO_pop(fbio);
  2090. BIO_free(fbio);
  2091. if (!foundit)
  2092. BIO_printf(bio_err,
  2093. "Didn't find STARTTLS in server response,"
  2094. " trying anyway...\n");
  2095. BIO_printf(sbio, ". STARTTLS\r\n");
  2096. BIO_read(sbio, sbuf, BUFSIZZ);
  2097. }
  2098. break;
  2099. case PROTO_FTP:
  2100. {
  2101. BIO *fbio = BIO_new(BIO_f_buffer());
  2102. BIO_push(fbio, sbio);
  2103. /* wait for multi-line response to end from FTP */
  2104. do {
  2105. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2106. }
  2107. while (mbuf_len > 3 && (!isdigit(mbuf[0]) || !isdigit(mbuf[1]) || !isdigit(mbuf[2]) || mbuf[3] != ' '));
  2108. (void)BIO_flush(fbio);
  2109. BIO_pop(fbio);
  2110. BIO_free(fbio);
  2111. BIO_printf(sbio, "AUTH TLS\r\n");
  2112. BIO_read(sbio, sbuf, BUFSIZZ);
  2113. }
  2114. break;
  2115. case PROTO_XMPP:
  2116. case PROTO_XMPP_SERVER:
  2117. {
  2118. int seen = 0;
  2119. BIO_printf(sbio, "<stream:stream "
  2120. "xmlns:stream='http://etherx.jabber.org/streams' "
  2121. "xmlns='jabber:%s' to='%s' version='1.0'>",
  2122. starttls_proto == PROTO_XMPP ? "client" : "server",
  2123. protohost ? protohost : host);
  2124. seen = BIO_read(sbio, mbuf, BUFSIZZ);
  2125. if (seen < 0) {
  2126. BIO_printf(bio_err, "BIO_read failed\n");
  2127. goto end;
  2128. }
  2129. mbuf[seen] = '\0';
  2130. while (!strstr
  2131. (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
  2132. && !strstr(mbuf,
  2133. "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
  2134. {
  2135. seen = BIO_read(sbio, mbuf, BUFSIZZ);
  2136. if (seen <= 0)
  2137. goto shut;
  2138. mbuf[seen] = '\0';
  2139. }
  2140. BIO_printf(sbio,
  2141. "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
  2142. seen = BIO_read(sbio, sbuf, BUFSIZZ);
  2143. if (seen < 0) {
  2144. BIO_printf(bio_err, "BIO_read failed\n");
  2145. goto shut;
  2146. }
  2147. sbuf[seen] = '\0';
  2148. if (!strstr(sbuf, "<proceed"))
  2149. goto shut;
  2150. mbuf[0] = '\0';
  2151. }
  2152. break;
  2153. case PROTO_TELNET:
  2154. {
  2155. static const unsigned char tls_do[] = {
  2156. /* IAC DO START_TLS */
  2157. 255, 253, 46
  2158. };
  2159. static const unsigned char tls_will[] = {
  2160. /* IAC WILL START_TLS */
  2161. 255, 251, 46
  2162. };
  2163. static const unsigned char tls_follows[] = {
  2164. /* IAC SB START_TLS FOLLOWS IAC SE */
  2165. 255, 250, 46, 1, 255, 240
  2166. };
  2167. int bytes;
  2168. /* Telnet server should demand we issue START_TLS */
  2169. bytes = BIO_read(sbio, mbuf, BUFSIZZ);
  2170. if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
  2171. goto shut;
  2172. /* Agree to issue START_TLS and send the FOLLOWS sub-command */
  2173. BIO_write(sbio, tls_will, 3);
  2174. BIO_write(sbio, tls_follows, 6);
  2175. (void)BIO_flush(sbio);
  2176. /* Telnet server also sent the FOLLOWS sub-command */
  2177. bytes = BIO_read(sbio, mbuf, BUFSIZZ);
  2178. if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
  2179. goto shut;
  2180. }
  2181. break;
  2182. case PROTO_CONNECT:
  2183. {
  2184. enum {
  2185. error_proto, /* Wrong protocol, not even HTTP */
  2186. error_connect, /* CONNECT failed */
  2187. success
  2188. } foundit = error_connect;
  2189. BIO *fbio = BIO_new(BIO_f_buffer());
  2190. BIO_push(fbio, sbio);
  2191. BIO_printf(fbio, "CONNECT %s HTTP/1.0\r\n\r\n", connectstr);
  2192. (void)BIO_flush(fbio);
  2193. /*
  2194. * The first line is the HTTP response. According to RFC 7230,
  2195. * it's formatted exactly like this:
  2196. *
  2197. * HTTP/d.d ddd Reason text\r\n
  2198. */
  2199. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2200. if (mbuf_len < (int)strlen("HTTP/1.0 200")) {
  2201. BIO_printf(bio_err,
  2202. "%s: HTTP CONNECT failed, insufficient response "
  2203. "from proxy (got %d octets)\n", prog, mbuf_len);
  2204. (void)BIO_flush(fbio);
  2205. BIO_pop(fbio);
  2206. BIO_free(fbio);
  2207. goto shut;
  2208. }
  2209. if (mbuf[8] != ' ') {
  2210. BIO_printf(bio_err,
  2211. "%s: HTTP CONNECT failed, incorrect response "
  2212. "from proxy\n", prog);
  2213. foundit = error_proto;
  2214. } else if (mbuf[9] != '2') {
  2215. BIO_printf(bio_err, "%s: HTTP CONNECT failed: %s ", prog,
  2216. &mbuf[9]);
  2217. } else {
  2218. foundit = success;
  2219. }
  2220. if (foundit != error_proto) {
  2221. /* Read past all following headers */
  2222. do {
  2223. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2224. } while (mbuf_len > 2);
  2225. }
  2226. (void)BIO_flush(fbio);
  2227. BIO_pop(fbio);
  2228. BIO_free(fbio);
  2229. if (foundit != success) {
  2230. goto shut;
  2231. }
  2232. }
  2233. break;
  2234. case PROTO_IRC:
  2235. {
  2236. int numeric;
  2237. BIO *fbio = BIO_new(BIO_f_buffer());
  2238. BIO_push(fbio, sbio);
  2239. BIO_printf(fbio, "STARTTLS\r\n");
  2240. (void)BIO_flush(fbio);
  2241. width = SSL_get_fd(con) + 1;
  2242. do {
  2243. numeric = 0;
  2244. FD_ZERO(&readfds);
  2245. openssl_fdset(SSL_get_fd(con), &readfds);
  2246. timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
  2247. timeout.tv_usec = 0;
  2248. /*
  2249. * If the IRCd doesn't respond within
  2250. * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
  2251. * it doesn't support STARTTLS. Many IRCds
  2252. * will not give _any_ sort of response to a
  2253. * STARTTLS command when it's not supported.
  2254. */
  2255. if (!BIO_get_buffer_num_lines(fbio)
  2256. && !BIO_pending(fbio)
  2257. && !BIO_pending(sbio)
  2258. && select(width, (void *)&readfds, NULL, NULL,
  2259. &timeout) < 1) {
  2260. BIO_printf(bio_err,
  2261. "Timeout waiting for response (%d seconds).\n",
  2262. S_CLIENT_IRC_READ_TIMEOUT);
  2263. break;
  2264. }
  2265. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2266. if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
  2267. break;
  2268. /* :example.net 451 STARTTLS :You have not registered */
  2269. /* :example.net 421 STARTTLS :Unknown command */
  2270. if ((numeric == 451 || numeric == 421)
  2271. && strstr(mbuf, "STARTTLS") != NULL) {
  2272. BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
  2273. break;
  2274. }
  2275. if (numeric == 691) {
  2276. BIO_printf(bio_err, "STARTTLS negotiation failed: ");
  2277. ERR_print_errors(bio_err);
  2278. break;
  2279. }
  2280. } while (numeric != 670);
  2281. (void)BIO_flush(fbio);
  2282. BIO_pop(fbio);
  2283. BIO_free(fbio);
  2284. if (numeric != 670) {
  2285. BIO_printf(bio_err, "Server does not support STARTTLS.\n");
  2286. ret = 1;
  2287. goto shut;
  2288. }
  2289. }
  2290. break;
  2291. case PROTO_MYSQL:
  2292. {
  2293. /* SSL request packet */
  2294. static const unsigned char ssl_req[] = {
  2295. /* payload_length, sequence_id */
  2296. 0x20, 0x00, 0x00, 0x01,
  2297. /* payload */
  2298. /* capability flags, CLIENT_SSL always set */
  2299. 0x85, 0xae, 0x7f, 0x00,
  2300. /* max-packet size */
  2301. 0x00, 0x00, 0x00, 0x01,
  2302. /* character set */
  2303. 0x21,
  2304. /* string[23] reserved (all [0]) */
  2305. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2306. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2307. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  2308. };
  2309. int bytes = 0;
  2310. int ssl_flg = 0x800;
  2311. int pos;
  2312. const unsigned char *packet = (const unsigned char *)sbuf;
  2313. /* Receiving Initial Handshake packet. */
  2314. bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
  2315. if (bytes < 0) {
  2316. BIO_printf(bio_err, "BIO_read failed\n");
  2317. goto shut;
  2318. /* Packet length[3], Packet number[1] + minimum payload[17] */
  2319. } else if (bytes < 21) {
  2320. BIO_printf(bio_err, "MySQL packet too short.\n");
  2321. goto shut;
  2322. } else if (bytes != (4 + packet[0] +
  2323. (packet[1] << 8) +
  2324. (packet[2] << 16))) {
  2325. BIO_printf(bio_err, "MySQL packet length does not match.\n");
  2326. goto shut;
  2327. /* protocol version[1] */
  2328. } else if (packet[4] != 0xA) {
  2329. BIO_printf(bio_err,
  2330. "Only MySQL protocol version 10 is supported.\n");
  2331. goto shut;
  2332. }
  2333. pos = 5;
  2334. /* server version[string+NULL] */
  2335. for (;;) {
  2336. if (pos >= bytes) {
  2337. BIO_printf(bio_err, "Cannot confirm server version. ");
  2338. goto shut;
  2339. } else if (packet[pos++] == '\0') {
  2340. break;
  2341. }
  2342. }
  2343. /* make sure we have at least 15 bytes left in the packet */
  2344. if (pos + 15 > bytes) {
  2345. BIO_printf(bio_err,
  2346. "MySQL server handshake packet is broken.\n");
  2347. goto shut;
  2348. }
  2349. pos += 12; /* skip over conn id[4] + SALT[8] */
  2350. if (packet[pos++] != '\0') { /* verify filler */
  2351. BIO_printf(bio_err,
  2352. "MySQL packet is broken.\n");
  2353. goto shut;
  2354. }
  2355. /* capability flags[2] */
  2356. if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
  2357. BIO_printf(bio_err, "MySQL server does not support SSL.\n");
  2358. goto shut;
  2359. }
  2360. /* Sending SSL Handshake packet. */
  2361. BIO_write(sbio, ssl_req, sizeof(ssl_req));
  2362. (void)BIO_flush(sbio);
  2363. }
  2364. break;
  2365. case PROTO_POSTGRES:
  2366. {
  2367. static const unsigned char ssl_request[] = {
  2368. /* Length SSLRequest */
  2369. 0, 0, 0, 8, 4, 210, 22, 47
  2370. };
  2371. int bytes;
  2372. /* Send SSLRequest packet */
  2373. BIO_write(sbio, ssl_request, 8);
  2374. (void)BIO_flush(sbio);
  2375. /* Reply will be a single S if SSL is enabled */
  2376. bytes = BIO_read(sbio, sbuf, BUFSIZZ);
  2377. if (bytes != 1 || sbuf[0] != 'S')
  2378. goto shut;
  2379. }
  2380. break;
  2381. case PROTO_NNTP:
  2382. {
  2383. int foundit = 0;
  2384. BIO *fbio = BIO_new(BIO_f_buffer());
  2385. BIO_push(fbio, sbio);
  2386. BIO_gets(fbio, mbuf, BUFSIZZ);
  2387. /* STARTTLS command requires CAPABILITIES... */
  2388. BIO_printf(fbio, "CAPABILITIES\r\n");
  2389. (void)BIO_flush(fbio);
  2390. /* wait for multi-line CAPABILITIES response */
  2391. do {
  2392. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2393. if (strstr(mbuf, "STARTTLS"))
  2394. foundit = 1;
  2395. } while (mbuf_len > 1 && mbuf[0] != '.');
  2396. (void)BIO_flush(fbio);
  2397. BIO_pop(fbio);
  2398. BIO_free(fbio);
  2399. if (!foundit)
  2400. BIO_printf(bio_err,
  2401. "Didn't find STARTTLS in server response,"
  2402. " trying anyway...\n");
  2403. BIO_printf(sbio, "STARTTLS\r\n");
  2404. mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
  2405. if (mbuf_len < 0) {
  2406. BIO_printf(bio_err, "BIO_read failed\n");
  2407. goto end;
  2408. }
  2409. mbuf[mbuf_len] = '\0';
  2410. if (strstr(mbuf, "382") == NULL) {
  2411. BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
  2412. goto shut;
  2413. }
  2414. }
  2415. break;
  2416. case PROTO_SIEVE:
  2417. {
  2418. int foundit = 0;
  2419. BIO *fbio = BIO_new(BIO_f_buffer());
  2420. BIO_push(fbio, sbio);
  2421. /* wait for multi-line response to end from Sieve */
  2422. do {
  2423. mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
  2424. /*
  2425. * According to RFC 5804 § 1.7, capability
  2426. * is case-insensitive, make it uppercase
  2427. */
  2428. if (mbuf_len > 1 && mbuf[0] == '"') {
  2429. make_uppercase(mbuf);
  2430. if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0)
  2431. foundit = 1;
  2432. }
  2433. } while (mbuf_len > 1 && mbuf[0] == '"');
  2434. (void)BIO_flush(fbio);
  2435. BIO_pop(fbio);
  2436. BIO_free(fbio);
  2437. if (!foundit)
  2438. BIO_printf(bio_err,
  2439. "Didn't find STARTTLS in server response,"
  2440. " trying anyway...\n");
  2441. BIO_printf(sbio, "STARTTLS\r\n");
  2442. mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
  2443. if (mbuf_len < 0) {
  2444. BIO_printf(bio_err, "BIO_read failed\n");
  2445. goto end;
  2446. }
  2447. mbuf[mbuf_len] = '\0';
  2448. if (mbuf_len < 2) {
  2449. BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
  2450. goto shut;
  2451. }
  2452. /*
  2453. * According to RFC 5804 § 2.2, response codes are case-
  2454. * insensitive, make it uppercase but preserve the response.
  2455. */
  2456. strncpy(sbuf, mbuf, 2);
  2457. make_uppercase(sbuf);
  2458. if (strncmp(sbuf, "OK", 2) != 0) {
  2459. BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
  2460. goto shut;
  2461. }
  2462. }
  2463. break;
  2464. case PROTO_LDAP:
  2465. {
  2466. /* StartTLS Operation according to RFC 4511 */
  2467. static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
  2468. "[LDAPMessage]\n"
  2469. "messageID=INTEGER:1\n"
  2470. "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
  2471. "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
  2472. long errline = -1;
  2473. char *genstr = NULL;
  2474. int result = -1;
  2475. ASN1_TYPE *atyp = NULL;
  2476. BIO *ldapbio = BIO_new(BIO_s_mem());
  2477. CONF *cnf = NCONF_new(NULL);
  2478. if (cnf == NULL) {
  2479. BIO_free(ldapbio);
  2480. goto end;
  2481. }
  2482. BIO_puts(ldapbio, ldap_tls_genconf);
  2483. if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
  2484. BIO_free(ldapbio);
  2485. NCONF_free(cnf);
  2486. if (errline <= 0) {
  2487. BIO_printf(bio_err, "NCONF_load_bio failed\n");
  2488. goto end;
  2489. } else {
  2490. BIO_printf(bio_err, "Error on line %ld\n", errline);
  2491. goto end;
  2492. }
  2493. }
  2494. BIO_free(ldapbio);
  2495. genstr = NCONF_get_string(cnf, "default", "asn1");
  2496. if (genstr == NULL) {
  2497. NCONF_free(cnf);
  2498. BIO_printf(bio_err, "NCONF_get_string failed\n");
  2499. goto end;
  2500. }
  2501. atyp = ASN1_generate_nconf(genstr, cnf);
  2502. if (atyp == NULL) {
  2503. NCONF_free(cnf);
  2504. BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
  2505. goto end;
  2506. }
  2507. NCONF_free(cnf);
  2508. /* Send SSLRequest packet */
  2509. BIO_write(sbio, atyp->value.sequence->data,
  2510. atyp->value.sequence->length);
  2511. (void)BIO_flush(sbio);
  2512. ASN1_TYPE_free(atyp);
  2513. mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
  2514. if (mbuf_len < 0) {
  2515. BIO_printf(bio_err, "BIO_read failed\n");
  2516. goto end;
  2517. }
  2518. result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
  2519. if (result < 0) {
  2520. BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
  2521. goto shut;
  2522. } else if (result > 0) {
  2523. BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
  2524. result);
  2525. goto shut;
  2526. }
  2527. mbuf_len = 0;
  2528. }
  2529. break;
  2530. }
  2531. if (early_data_file != NULL
  2532. && ((SSL_get0_session(con) != NULL
  2533. && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
  2534. || (psksess != NULL
  2535. && SSL_SESSION_get_max_early_data(psksess) > 0))) {
  2536. BIO *edfile = BIO_new_file(early_data_file, "r");
  2537. size_t readbytes, writtenbytes;
  2538. int finish = 0;
  2539. if (edfile == NULL) {
  2540. BIO_printf(bio_err, "Cannot open early data file\n");
  2541. goto shut;
  2542. }
  2543. while (!finish) {
  2544. if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
  2545. finish = 1;
  2546. while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
  2547. switch (SSL_get_error(con, 0)) {
  2548. case SSL_ERROR_WANT_WRITE:
  2549. case SSL_ERROR_WANT_ASYNC:
  2550. case SSL_ERROR_WANT_READ:
  2551. /* Just keep trying - busy waiting */
  2552. continue;
  2553. default:
  2554. BIO_printf(bio_err, "Error writing early data\n");
  2555. BIO_free(edfile);
  2556. ERR_print_errors(bio_err);
  2557. goto shut;
  2558. }
  2559. }
  2560. }
  2561. BIO_free(edfile);
  2562. }
  2563. for (;;) {
  2564. FD_ZERO(&readfds);
  2565. FD_ZERO(&writefds);
  2566. if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
  2567. timeoutp = &timeout;
  2568. else
  2569. timeoutp = NULL;
  2570. if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
  2571. && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
  2572. in_init = 1;
  2573. tty_on = 0;
  2574. } else {
  2575. tty_on = 1;
  2576. if (in_init) {
  2577. in_init = 0;
  2578. if (c_brief) {
  2579. BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
  2580. print_ssl_summary(con);
  2581. }
  2582. print_stuff(bio_c_out, con, full_log);
  2583. if (full_log > 0)
  2584. full_log--;
  2585. if (starttls_proto) {
  2586. BIO_write(bio_err, mbuf, mbuf_len);
  2587. /* We don't need to know any more */
  2588. if (!reconnect)
  2589. starttls_proto = PROTO_OFF;
  2590. }
  2591. if (reconnect) {
  2592. reconnect--;
  2593. BIO_printf(bio_c_out,
  2594. "drop connection and then reconnect\n");
  2595. do_ssl_shutdown(con);
  2596. SSL_set_connect_state(con);
  2597. BIO_closesocket(SSL_get_fd(con));
  2598. goto re_start;
  2599. }
  2600. }
  2601. }
  2602. ssl_pending = read_ssl && SSL_has_pending(con);
  2603. if (!ssl_pending) {
  2604. #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
  2605. if (tty_on) {
  2606. /*
  2607. * Note that select() returns when read _would not block_,
  2608. * and EOF satisfies that. To avoid a CPU-hogging loop,
  2609. * set the flag so we exit.
  2610. */
  2611. if (read_tty && !at_eof)
  2612. openssl_fdset(fileno_stdin(), &readfds);
  2613. #if !defined(OPENSSL_SYS_VMS)
  2614. if (write_tty)
  2615. openssl_fdset(fileno_stdout(), &writefds);
  2616. #endif
  2617. }
  2618. if (read_ssl)
  2619. openssl_fdset(SSL_get_fd(con), &readfds);
  2620. if (write_ssl)
  2621. openssl_fdset(SSL_get_fd(con), &writefds);
  2622. #else
  2623. if (!tty_on || !write_tty) {
  2624. if (read_ssl)
  2625. openssl_fdset(SSL_get_fd(con), &readfds);
  2626. if (write_ssl)
  2627. openssl_fdset(SSL_get_fd(con), &writefds);
  2628. }
  2629. #endif
  2630. /*
  2631. * Note: under VMS with SOCKETSHR the second parameter is
  2632. * currently of type (int *) whereas under other systems it is
  2633. * (void *) if you don't have a cast it will choke the compiler:
  2634. * if you do have a cast then you can either go for (int *) or
  2635. * (void *).
  2636. */
  2637. #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
  2638. /*
  2639. * Under Windows/DOS we make the assumption that we can always
  2640. * write to the tty: therefore if we need to write to the tty we
  2641. * just fall through. Otherwise we timeout the select every
  2642. * second and see if there are any keypresses. Note: this is a
  2643. * hack, in a proper Windows application we wouldn't do this.
  2644. */
  2645. i = 0;
  2646. if (!write_tty) {
  2647. if (read_tty) {
  2648. tv.tv_sec = 1;
  2649. tv.tv_usec = 0;
  2650. i = select(width, (void *)&readfds, (void *)&writefds,
  2651. NULL, &tv);
  2652. if (!i && (!has_stdin_waiting() || !read_tty))
  2653. continue;
  2654. } else
  2655. i = select(width, (void *)&readfds, (void *)&writefds,
  2656. NULL, timeoutp);
  2657. }
  2658. #else
  2659. i = select(width, (void *)&readfds, (void *)&writefds,
  2660. NULL, timeoutp);
  2661. #endif
  2662. if (i < 0) {
  2663. BIO_printf(bio_err, "bad select %d\n",
  2664. get_last_socket_error());
  2665. goto shut;
  2666. }
  2667. }
  2668. if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
  2669. BIO_printf(bio_err, "TIMEOUT occurred\n");
  2670. if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
  2671. k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
  2672. switch (SSL_get_error(con, k)) {
  2673. case SSL_ERROR_NONE:
  2674. cbuf_off += k;
  2675. cbuf_len -= k;
  2676. if (k <= 0)
  2677. goto end;
  2678. /* we have done a write(con,NULL,0); */
  2679. if (cbuf_len <= 0) {
  2680. read_tty = 1;
  2681. write_ssl = 0;
  2682. } else { /* if (cbuf_len > 0) */
  2683. read_tty = 0;
  2684. write_ssl = 1;
  2685. }
  2686. break;
  2687. case SSL_ERROR_WANT_WRITE:
  2688. BIO_printf(bio_c_out, "write W BLOCK\n");
  2689. write_ssl = 1;
  2690. read_tty = 0;
  2691. break;
  2692. case SSL_ERROR_WANT_ASYNC:
  2693. BIO_printf(bio_c_out, "write A BLOCK\n");
  2694. wait_for_async(con);
  2695. write_ssl = 1;
  2696. read_tty = 0;
  2697. break;
  2698. case SSL_ERROR_WANT_READ:
  2699. BIO_printf(bio_c_out, "write R BLOCK\n");
  2700. write_tty = 0;
  2701. read_ssl = 1;
  2702. write_ssl = 0;
  2703. break;
  2704. case SSL_ERROR_WANT_X509_LOOKUP:
  2705. BIO_printf(bio_c_out, "write X BLOCK\n");
  2706. break;
  2707. case SSL_ERROR_ZERO_RETURN:
  2708. if (cbuf_len != 0) {
  2709. BIO_printf(bio_c_out, "shutdown\n");
  2710. ret = 0;
  2711. goto shut;
  2712. } else {
  2713. read_tty = 1;
  2714. write_ssl = 0;
  2715. break;
  2716. }
  2717. case SSL_ERROR_SYSCALL:
  2718. if ((k != 0) || (cbuf_len != 0)) {
  2719. BIO_printf(bio_err, "write:errno=%d\n",
  2720. get_last_socket_error());
  2721. goto shut;
  2722. } else {
  2723. read_tty = 1;
  2724. write_ssl = 0;
  2725. }
  2726. break;
  2727. case SSL_ERROR_WANT_ASYNC_JOB:
  2728. /* This shouldn't ever happen in s_client - treat as an error */
  2729. case SSL_ERROR_SSL:
  2730. ERR_print_errors(bio_err);
  2731. goto shut;
  2732. }
  2733. }
  2734. #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
  2735. /* Assume Windows/DOS/BeOS can always write */
  2736. else if (!ssl_pending && write_tty)
  2737. #else
  2738. else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
  2739. #endif
  2740. {
  2741. #ifdef CHARSET_EBCDIC
  2742. ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
  2743. #endif
  2744. i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
  2745. if (i <= 0) {
  2746. BIO_printf(bio_c_out, "DONE\n");
  2747. ret = 0;
  2748. goto shut;
  2749. }
  2750. sbuf_len -= i;
  2751. sbuf_off += i;
  2752. if (sbuf_len <= 0) {
  2753. read_ssl = 1;
  2754. write_tty = 0;
  2755. }
  2756. } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
  2757. #ifdef RENEG
  2758. {
  2759. static int iiii;
  2760. if (++iiii == 52) {
  2761. SSL_renegotiate(con);
  2762. iiii = 0;
  2763. }
  2764. }
  2765. #endif
  2766. k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
  2767. switch (SSL_get_error(con, k)) {
  2768. case SSL_ERROR_NONE:
  2769. if (k <= 0)
  2770. goto end;
  2771. sbuf_off = 0;
  2772. sbuf_len = k;
  2773. read_ssl = 0;
  2774. write_tty = 1;
  2775. break;
  2776. case SSL_ERROR_WANT_ASYNC:
  2777. BIO_printf(bio_c_out, "read A BLOCK\n");
  2778. wait_for_async(con);
  2779. write_tty = 0;
  2780. read_ssl = 1;
  2781. if ((read_tty == 0) && (write_ssl == 0))
  2782. write_ssl = 1;
  2783. break;
  2784. case SSL_ERROR_WANT_WRITE:
  2785. BIO_printf(bio_c_out, "read W BLOCK\n");
  2786. write_ssl = 1;
  2787. read_tty = 0;
  2788. break;
  2789. case SSL_ERROR_WANT_READ:
  2790. BIO_printf(bio_c_out, "read R BLOCK\n");
  2791. write_tty = 0;
  2792. read_ssl = 1;
  2793. if ((read_tty == 0) && (write_ssl == 0))
  2794. write_ssl = 1;
  2795. break;
  2796. case SSL_ERROR_WANT_X509_LOOKUP:
  2797. BIO_printf(bio_c_out, "read X BLOCK\n");
  2798. break;
  2799. case SSL_ERROR_SYSCALL:
  2800. ret = get_last_socket_error();
  2801. if (c_brief)
  2802. BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
  2803. else
  2804. BIO_printf(bio_err, "read:errno=%d\n", ret);
  2805. goto shut;
  2806. case SSL_ERROR_ZERO_RETURN:
  2807. BIO_printf(bio_c_out, "closed\n");
  2808. ret = 0;
  2809. goto shut;
  2810. case SSL_ERROR_WANT_ASYNC_JOB:
  2811. /* This shouldn't ever happen in s_client. Treat as an error */
  2812. case SSL_ERROR_SSL:
  2813. ERR_print_errors(bio_err);
  2814. goto shut;
  2815. }
  2816. }
  2817. /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
  2818. #if defined(OPENSSL_SYS_MSDOS)
  2819. else if (has_stdin_waiting())
  2820. #else
  2821. else if (FD_ISSET(fileno_stdin(), &readfds))
  2822. #endif
  2823. {
  2824. if (crlf) {
  2825. int j, lf_num;
  2826. i = raw_read_stdin(cbuf, BUFSIZZ / 2);
  2827. lf_num = 0;
  2828. /* both loops are skipped when i <= 0 */
  2829. for (j = 0; j < i; j++)
  2830. if (cbuf[j] == '\n')
  2831. lf_num++;
  2832. for (j = i - 1; j >= 0; j--) {
  2833. cbuf[j + lf_num] = cbuf[j];
  2834. if (cbuf[j] == '\n') {
  2835. lf_num--;
  2836. i++;
  2837. cbuf[j + lf_num] = '\r';
  2838. }
  2839. }
  2840. assert(lf_num == 0);
  2841. } else
  2842. i = raw_read_stdin(cbuf, BUFSIZZ);
  2843. #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
  2844. if (i == 0)
  2845. at_eof = 1;
  2846. #endif
  2847. if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
  2848. BIO_printf(bio_err, "DONE\n");
  2849. ret = 0;
  2850. goto shut;
  2851. }
  2852. if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
  2853. BIO_printf(bio_err, "RENEGOTIATING\n");
  2854. SSL_renegotiate(con);
  2855. cbuf_len = 0;
  2856. } else if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' )
  2857. && cmdletters) {
  2858. BIO_printf(bio_err, "KEYUPDATE\n");
  2859. SSL_key_update(con,
  2860. cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
  2861. : SSL_KEY_UPDATE_NOT_REQUESTED);
  2862. cbuf_len = 0;
  2863. }
  2864. #ifndef OPENSSL_NO_HEARTBEATS
  2865. else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) {
  2866. BIO_printf(bio_err, "HEARTBEATING\n");
  2867. SSL_heartbeat(con);
  2868. cbuf_len = 0;
  2869. }
  2870. #endif
  2871. else {
  2872. cbuf_len = i;
  2873. cbuf_off = 0;
  2874. #ifdef CHARSET_EBCDIC
  2875. ebcdic2ascii(cbuf, cbuf, i);
  2876. #endif
  2877. }
  2878. write_ssl = 1;
  2879. read_tty = 0;
  2880. }
  2881. }
  2882. ret = 0;
  2883. shut:
  2884. if (in_init)
  2885. print_stuff(bio_c_out, con, full_log);
  2886. do_ssl_shutdown(con);
  2887. /*
  2888. * If we ended with an alert being sent, but still with data in the
  2889. * network buffer to be read, then calling BIO_closesocket() will
  2890. * result in a TCP-RST being sent. On some platforms (notably
  2891. * Windows) then this will result in the peer immediately abandoning
  2892. * the connection including any buffered alert data before it has
  2893. * had a chance to be read. Shutting down the sending side first,
  2894. * and then closing the socket sends TCP-FIN first followed by
  2895. * TCP-RST. This seems to allow the peer to read the alert data.
  2896. */
  2897. shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
  2898. /*
  2899. * We just said we have nothing else to say, but it doesn't mean that
  2900. * the other side has nothing. It's even recommended to consume incoming
  2901. * data. [In testing context this ensures that alerts are passed on...]
  2902. */
  2903. timeout.tv_sec = 0;
  2904. timeout.tv_usec = 500000; /* some extreme round-trip */
  2905. do {
  2906. FD_ZERO(&readfds);
  2907. openssl_fdset(s, &readfds);
  2908. } while (select(s + 1, &readfds, NULL, NULL, &timeout) > 0
  2909. && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
  2910. BIO_closesocket(SSL_get_fd(con));
  2911. end:
  2912. if (con != NULL) {
  2913. if (prexit != 0)
  2914. print_stuff(bio_c_out, con, 1);
  2915. SSL_free(con);
  2916. }
  2917. SSL_SESSION_free(psksess);
  2918. #if !defined(OPENSSL_NO_NEXTPROTONEG)
  2919. OPENSSL_free(next_proto.data);
  2920. #endif
  2921. SSL_CTX_free(ctx);
  2922. set_keylog_file(NULL, NULL);
  2923. X509_free(cert);
  2924. sk_X509_CRL_pop_free(crls, X509_CRL_free);
  2925. EVP_PKEY_free(key);
  2926. sk_X509_pop_free(chain, X509_free);
  2927. OPENSSL_free(pass);
  2928. #ifndef OPENSSL_NO_SRP
  2929. OPENSSL_free(srp_arg.srppassin);
  2930. #endif
  2931. OPENSSL_free(connectstr);
  2932. OPENSSL_free(bindstr);
  2933. OPENSSL_free(host);
  2934. OPENSSL_free(port);
  2935. X509_VERIFY_PARAM_free(vpm);
  2936. ssl_excert_free(exc);
  2937. sk_OPENSSL_STRING_free(ssl_args);
  2938. sk_OPENSSL_STRING_free(dane_tlsa_rrset);
  2939. SSL_CONF_CTX_free(cctx);
  2940. OPENSSL_clear_free(cbuf, BUFSIZZ);
  2941. OPENSSL_clear_free(sbuf, BUFSIZZ);
  2942. OPENSSL_clear_free(mbuf, BUFSIZZ);
  2943. release_engine(e);
  2944. BIO_free(bio_c_out);
  2945. bio_c_out = NULL;
  2946. BIO_free(bio_c_msg);
  2947. bio_c_msg = NULL;
  2948. return ret;
  2949. }
  2950. static void print_stuff(BIO *bio, SSL *s, int full)
  2951. {
  2952. X509 *peer = NULL;
  2953. STACK_OF(X509) *sk;
  2954. const SSL_CIPHER *c;
  2955. int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
  2956. long verify_result;
  2957. #ifndef OPENSSL_NO_COMP
  2958. const COMP_METHOD *comp, *expansion;
  2959. #endif
  2960. unsigned char *exportedkeymat;
  2961. #ifndef OPENSSL_NO_CT
  2962. const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
  2963. #endif
  2964. if (full) {
  2965. int got_a_chain = 0;
  2966. sk = SSL_get_peer_cert_chain(s);
  2967. if (sk != NULL) {
  2968. got_a_chain = 1;
  2969. BIO_printf(bio, "---\nCertificate chain\n");
  2970. for (i = 0; i < sk_X509_num(sk); i++) {
  2971. BIO_printf(bio, "%2d s:", i);
  2972. X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
  2973. BIO_puts(bio, "\n");
  2974. BIO_printf(bio, " i:");
  2975. X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
  2976. BIO_puts(bio, "\n");
  2977. if (c_showcerts)
  2978. PEM_write_bio_X509(bio, sk_X509_value(sk, i));
  2979. }
  2980. }
  2981. BIO_printf(bio, "---\n");
  2982. peer = SSL_get_peer_certificate(s);
  2983. if (peer != NULL) {
  2984. BIO_printf(bio, "Server certificate\n");
  2985. /* Redundant if we showed the whole chain */
  2986. if (!(c_showcerts && got_a_chain))
  2987. PEM_write_bio_X509(bio, peer);
  2988. dump_cert_text(bio, peer);
  2989. } else {
  2990. BIO_printf(bio, "no peer certificate available\n");
  2991. }
  2992. print_ca_names(bio, s);
  2993. ssl_print_sigalgs(bio, s);
  2994. ssl_print_tmp_key(bio, s);
  2995. #ifndef OPENSSL_NO_CT
  2996. /*
  2997. * When the SSL session is anonymous, or resumed via an abbreviated
  2998. * handshake, no SCTs are provided as part of the handshake. While in
  2999. * a resumed session SCTs may be present in the session's certificate,
  3000. * no callbacks are invoked to revalidate these, and in any case that
  3001. * set of SCTs may be incomplete. Thus it makes little sense to
  3002. * attempt to display SCTs from a resumed session's certificate, and of
  3003. * course none are associated with an anonymous peer.
  3004. */
  3005. if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
  3006. const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
  3007. int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
  3008. BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
  3009. if (sct_count > 0) {
  3010. const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
  3011. BIO_printf(bio, "---\n");
  3012. for (i = 0; i < sct_count; ++i) {
  3013. SCT *sct = sk_SCT_value(scts, i);
  3014. BIO_printf(bio, "SCT validation status: %s\n",
  3015. SCT_validation_status_string(sct));
  3016. SCT_print(sct, bio, 0, log_store);
  3017. if (i < sct_count - 1)
  3018. BIO_printf(bio, "\n---\n");
  3019. }
  3020. BIO_printf(bio, "\n");
  3021. }
  3022. }
  3023. #endif
  3024. BIO_printf(bio,
  3025. "---\nSSL handshake has read %ju bytes "
  3026. "and written %ju bytes\n",
  3027. BIO_number_read(SSL_get_rbio(s)),
  3028. BIO_number_written(SSL_get_wbio(s)));
  3029. }
  3030. print_verify_detail(s, bio);
  3031. BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
  3032. c = SSL_get_current_cipher(s);
  3033. BIO_printf(bio, "%s, Cipher is %s\n",
  3034. SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
  3035. if (peer != NULL) {
  3036. EVP_PKEY *pktmp;
  3037. pktmp = X509_get0_pubkey(peer);
  3038. BIO_printf(bio, "Server public key is %d bit\n",
  3039. EVP_PKEY_bits(pktmp));
  3040. }
  3041. BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
  3042. SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
  3043. #ifndef OPENSSL_NO_COMP
  3044. comp = SSL_get_current_compression(s);
  3045. expansion = SSL_get_current_expansion(s);
  3046. BIO_printf(bio, "Compression: %s\n",
  3047. comp ? SSL_COMP_get_name(comp) : "NONE");
  3048. BIO_printf(bio, "Expansion: %s\n",
  3049. expansion ? SSL_COMP_get_name(expansion) : "NONE");
  3050. #endif
  3051. #ifdef SSL_DEBUG
  3052. {
  3053. /* Print out local port of connection: useful for debugging */
  3054. int sock;
  3055. union BIO_sock_info_u info;
  3056. sock = SSL_get_fd(s);
  3057. if ((info.addr = BIO_ADDR_new()) != NULL
  3058. && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
  3059. BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
  3060. ntohs(BIO_ADDR_rawport(info.addr)));
  3061. }
  3062. BIO_ADDR_free(info.addr);
  3063. }
  3064. #endif
  3065. #if !defined(OPENSSL_NO_NEXTPROTONEG)
  3066. if (next_proto.status != -1) {
  3067. const unsigned char *proto;
  3068. unsigned int proto_len;
  3069. SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
  3070. BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
  3071. BIO_write(bio, proto, proto_len);
  3072. BIO_write(bio, "\n", 1);
  3073. }
  3074. #endif
  3075. {
  3076. const unsigned char *proto;
  3077. unsigned int proto_len;
  3078. SSL_get0_alpn_selected(s, &proto, &proto_len);
  3079. if (proto_len > 0) {
  3080. BIO_printf(bio, "ALPN protocol: ");
  3081. BIO_write(bio, proto, proto_len);
  3082. BIO_write(bio, "\n", 1);
  3083. } else
  3084. BIO_printf(bio, "No ALPN negotiated\n");
  3085. }
  3086. #ifndef OPENSSL_NO_SRTP
  3087. {
  3088. SRTP_PROTECTION_PROFILE *srtp_profile =
  3089. SSL_get_selected_srtp_profile(s);
  3090. if (srtp_profile)
  3091. BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
  3092. srtp_profile->name);
  3093. }
  3094. #endif
  3095. if (istls13) {
  3096. switch (SSL_get_early_data_status(s)) {
  3097. case SSL_EARLY_DATA_NOT_SENT:
  3098. BIO_printf(bio, "Early data was not sent\n");
  3099. break;
  3100. case SSL_EARLY_DATA_REJECTED:
  3101. BIO_printf(bio, "Early data was rejected\n");
  3102. break;
  3103. case SSL_EARLY_DATA_ACCEPTED:
  3104. BIO_printf(bio, "Early data was accepted\n");
  3105. break;
  3106. }
  3107. /*
  3108. * We also print the verify results when we dump session information,
  3109. * but in TLSv1.3 we may not get that right away (or at all) depending
  3110. * on when we get a NewSessionTicket. Therefore we print it now as well.
  3111. */
  3112. verify_result = SSL_get_verify_result(s);
  3113. BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
  3114. X509_verify_cert_error_string(verify_result));
  3115. } else {
  3116. /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
  3117. SSL_SESSION_print(bio, SSL_get_session(s));
  3118. }
  3119. if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
  3120. BIO_printf(bio, "Keying material exporter:\n");
  3121. BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
  3122. BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
  3123. exportedkeymat = app_malloc(keymatexportlen, "export key");
  3124. if (!SSL_export_keying_material(s, exportedkeymat,
  3125. keymatexportlen,
  3126. keymatexportlabel,
  3127. strlen(keymatexportlabel),
  3128. NULL, 0, 0)) {
  3129. BIO_printf(bio, " Error\n");
  3130. } else {
  3131. BIO_printf(bio, " Keying material: ");
  3132. for (i = 0; i < keymatexportlen; i++)
  3133. BIO_printf(bio, "%02X", exportedkeymat[i]);
  3134. BIO_printf(bio, "\n");
  3135. }
  3136. OPENSSL_free(exportedkeymat);
  3137. }
  3138. BIO_printf(bio, "---\n");
  3139. X509_free(peer);
  3140. /* flush, or debugging output gets mixed with http response */
  3141. (void)BIO_flush(bio);
  3142. }
  3143. # ifndef OPENSSL_NO_OCSP
  3144. static int ocsp_resp_cb(SSL *s, void *arg)
  3145. {
  3146. const unsigned char *p;
  3147. int len;
  3148. OCSP_RESPONSE *rsp;
  3149. len = SSL_get_tlsext_status_ocsp_resp(s, &p);
  3150. BIO_puts(arg, "OCSP response: ");
  3151. if (p == NULL) {
  3152. BIO_puts(arg, "no response sent\n");
  3153. return 1;
  3154. }
  3155. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  3156. if (rsp == NULL) {
  3157. BIO_puts(arg, "response parse error\n");
  3158. BIO_dump_indent(arg, (char *)p, len, 4);
  3159. return 0;
  3160. }
  3161. BIO_puts(arg, "\n======================================\n");
  3162. OCSP_RESPONSE_print(arg, rsp, 0);
  3163. BIO_puts(arg, "======================================\n");
  3164. OCSP_RESPONSE_free(rsp);
  3165. return 1;
  3166. }
  3167. # endif
  3168. static int ldap_ExtendedResponse_parse(const char *buf, long rem)
  3169. {
  3170. const unsigned char *cur, *end;
  3171. long len;
  3172. int tag, xclass, inf, ret = -1;
  3173. cur = (const unsigned char *)buf;
  3174. end = cur + rem;
  3175. /*
  3176. * From RFC 4511:
  3177. *
  3178. * LDAPMessage ::= SEQUENCE {
  3179. * messageID MessageID,
  3180. * protocolOp CHOICE {
  3181. * ...
  3182. * extendedResp ExtendedResponse,
  3183. * ... },
  3184. * controls [0] Controls OPTIONAL }
  3185. *
  3186. * ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
  3187. * COMPONENTS OF LDAPResult,
  3188. * responseName [10] LDAPOID OPTIONAL,
  3189. * responseValue [11] OCTET STRING OPTIONAL }
  3190. *
  3191. * LDAPResult ::= SEQUENCE {
  3192. * resultCode ENUMERATED {
  3193. * success (0),
  3194. * ...
  3195. * other (80),
  3196. * ... },
  3197. * matchedDN LDAPDN,
  3198. * diagnosticMessage LDAPString,
  3199. * referral [3] Referral OPTIONAL }
  3200. */
  3201. /* pull SEQUENCE */
  3202. inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
  3203. if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
  3204. (rem = end - cur, len > rem)) {
  3205. BIO_printf(bio_err, "Unexpected LDAP response\n");
  3206. goto end;
  3207. }
  3208. rem = len; /* ensure that we don't overstep the SEQUENCE */
  3209. /* pull MessageID */
  3210. inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
  3211. if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
  3212. (rem = end - cur, len > rem)) {
  3213. BIO_printf(bio_err, "No MessageID\n");
  3214. goto end;
  3215. }
  3216. cur += len; /* shall we check for MessageId match or just skip? */
  3217. /* pull [APPLICATION 24] */
  3218. rem = end - cur;
  3219. inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
  3220. if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
  3221. tag != 24) {
  3222. BIO_printf(bio_err, "Not ExtendedResponse\n");
  3223. goto end;
  3224. }
  3225. /* pull resultCode */
  3226. rem = end - cur;
  3227. inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
  3228. if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
  3229. (rem = end - cur, len > rem)) {
  3230. BIO_printf(bio_err, "Not LDAPResult\n");
  3231. goto end;
  3232. }
  3233. /* len should always be one, but just in case... */
  3234. for (ret = 0, inf = 0; inf < len; inf++) {
  3235. ret <<= 8;
  3236. ret |= cur[inf];
  3237. }
  3238. /* There is more data, but we don't care... */
  3239. end:
  3240. return ret;
  3241. }
  3242. /*
  3243. * Host dNS Name verifier: used for checking that the hostname is in dNS format
  3244. * before setting it as SNI
  3245. */
  3246. static int is_dNS_name(const char *host)
  3247. {
  3248. const size_t MAX_LABEL_LENGTH = 63;
  3249. size_t i;
  3250. int isdnsname = 0;
  3251. size_t length = strlen(host);
  3252. size_t label_length = 0;
  3253. int all_numeric = 1;
  3254. /*
  3255. * Deviation from strict DNS name syntax, also check names with '_'
  3256. * Check DNS name syntax, any '-' or '.' must be internal,
  3257. * and on either side of each '.' we can't have a '-' or '.'.
  3258. *
  3259. * If the name has just one label, we don't consider it a DNS name.
  3260. */
  3261. for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
  3262. char c = host[i];
  3263. if ((c >= 'a' && c <= 'z')
  3264. || (c >= 'A' && c <= 'Z')
  3265. || c == '_') {
  3266. label_length += 1;
  3267. all_numeric = 0;
  3268. continue;
  3269. }
  3270. if (c >= '0' && c <= '9') {
  3271. label_length += 1;
  3272. continue;
  3273. }
  3274. /* Dot and hyphen cannot be first or last. */
  3275. if (i > 0 && i < length - 1) {
  3276. if (c == '-') {
  3277. label_length += 1;
  3278. continue;
  3279. }
  3280. /*
  3281. * Next to a dot the preceding and following characters must not be
  3282. * another dot or a hyphen. Otherwise, record that the name is
  3283. * plausible, since it has two or more labels.
  3284. */
  3285. if (c == '.'
  3286. && host[i + 1] != '.'
  3287. && host[i - 1] != '-'
  3288. && host[i + 1] != '-') {
  3289. label_length = 0;
  3290. isdnsname = 1;
  3291. continue;
  3292. }
  3293. }
  3294. isdnsname = 0;
  3295. break;
  3296. }
  3297. /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
  3298. isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
  3299. return isdnsname;
  3300. }
  3301. #endif /* OPENSSL_NO_SOCK */