s_client.c 117 KB

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