s_client.c 117 KB

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