s_client.c 115 KB

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