s_client.c 117 KB

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