s_client.c 113 KB

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