s_client.c 117 KB

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