s_client.c 111 KB

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