s_client.c 113 KB

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