s_client.c 116 KB

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