s_client.c 133 KB

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