s_client.c 117 KB

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