s_client.c 112 KB

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