2
0

s_client.c 132 KB

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