s_client.c 117 KB

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