s_client.c 115 KB

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