transport2.c 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868
  1. /*
  2. * Packet protocol layer for the SSH-2 transport protocol (RFC 4253).
  3. */
  4. #include <assert.h>
  5. #include "putty.h"
  6. #include "ssh.h"
  7. #include "bpp.h"
  8. #include "ppl.h"
  9. #include "sshcr.h"
  10. #ifndef WINSCP
  11. #include "server.h"
  12. #endif
  13. #include "storage.h"
  14. #include "transport2.h"
  15. #include "mpint.h"
  16. const struct ssh_signkey_with_user_pref_id ssh2_hostkey_algs[] = {
  17. #define ARRAYENT_HOSTKEY_ALGORITHM(type, alg) { &alg, type },
  18. HOSTKEY_ALGORITHMS(ARRAYENT_HOSTKEY_ALGORITHM)
  19. };
  20. const static ssh2_macalg *const macs[] = {
  21. &ssh_hmac_sha256, &ssh_hmac_sha512,
  22. &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  23. };
  24. const static ssh2_macalg *const buggymacs[] = {
  25. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  26. };
  27. const static ptrlen ext_info_c = PTRLEN_DECL_LITERAL("ext-info-c");
  28. const static ptrlen ext_info_s = PTRLEN_DECL_LITERAL("ext-info-s");
  29. const static ptrlen kex_strict_c =
  30. PTRLEN_DECL_LITERAL("[email protected]");
  31. const static ptrlen kex_strict_s =
  32. PTRLEN_DECL_LITERAL("[email protected]");
  33. /* Pointer value to store in s->weak_algorithms_consented_to to
  34. * indicate that the user has accepted the risk of the Terrapin
  35. * attack */
  36. static const char terrapin_weakness[1];
  37. static ssh_compressor *ssh_comp_none_init(void)
  38. {
  39. return NULL;
  40. }
  41. static void ssh_comp_none_cleanup(ssh_compressor *handle)
  42. {
  43. }
  44. static ssh_decompressor *ssh_decomp_none_init(void)
  45. {
  46. return NULL;
  47. }
  48. static void ssh_decomp_none_cleanup(ssh_decompressor *handle)
  49. {
  50. }
  51. static void ssh_comp_none_block(ssh_compressor *handle,
  52. const unsigned char *block, int len,
  53. unsigned char **outblock, int *outlen,
  54. int minlen)
  55. {
  56. }
  57. static bool ssh_decomp_none_block(ssh_decompressor *handle,
  58. const unsigned char *block, int len,
  59. unsigned char **outblock, int *outlen)
  60. {
  61. return false;
  62. }
  63. static const ssh_compression_alg ssh_comp_none = {
  64. // WINSCP
  65. /*.name =*/ "none",
  66. /*.delayed_name =*/ NULL,
  67. /*.compress_new =*/ ssh_comp_none_init,
  68. /*.compress_free =*/ ssh_comp_none_cleanup,
  69. /*.compress =*/ ssh_comp_none_block,
  70. /*.decompress_new =*/ ssh_decomp_none_init,
  71. /*.decompress_free =*/ ssh_decomp_none_cleanup,
  72. /*.decompress =*/ ssh_decomp_none_block,
  73. /*.text_name =*/ NULL,
  74. };
  75. const static ssh_compression_alg *const compressions[] = {
  76. &ssh_zlib, &ssh_comp_none
  77. };
  78. static void ssh2_transport_free(PacketProtocolLayer *);
  79. static void ssh2_transport_process_queue(PacketProtocolLayer *);
  80. static bool ssh2_transport_get_specials(
  81. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx);
  82. static void ssh2_transport_special_cmd(PacketProtocolLayer *ppl,
  83. SessionSpecialCode code, int arg);
  84. static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf);
  85. static size_t ssh2_transport_queued_data_size(PacketProtocolLayer *ppl);
  86. static void ssh2_transport_set_max_data_size(struct ssh2_transport_state *s);
  87. static unsigned long sanitise_rekey_time(int rekey_time, unsigned long def);
  88. static void ssh2_transport_higher_layer_packet_callback(void *context);
  89. static void ssh2_transport_final_output(PacketProtocolLayer *ppl);
  90. static const char *terrapin_vulnerable(
  91. bool strict_kex, const transport_direction *d);
  92. static bool try_to_avoid_terrapin(const struct ssh2_transport_state *s);
  93. static unsigned int ssh2_transport_winscp_query(PacketProtocolLayer *ppl, int query);
  94. static const PacketProtocolLayerVtable ssh2_transport_vtable = {
  95. // WINSCP
  96. /*.free =*/ ssh2_transport_free,
  97. /*.process_queue =*/ ssh2_transport_process_queue,
  98. /*.get_specials =*/ ssh2_transport_get_specials,
  99. /*.special_cmd =*/ ssh2_transport_special_cmd,
  100. /*.reconfigure =*/ ssh2_transport_reconfigure,
  101. /*.queued_data_size =*/ ssh2_transport_queued_data_size,
  102. /*.final_output =*/ ssh2_transport_final_output,
  103. /*.name =*/ NULL, /* no protocol name for this layer */
  104. ssh2_transport_winscp_query,
  105. };
  106. #ifndef NO_GSSAPI
  107. static void ssh2_transport_gss_update(struct ssh2_transport_state *s,
  108. bool definitely_rekeying);
  109. #endif
  110. static bool ssh2_transport_timer_update(struct ssh2_transport_state *s,
  111. unsigned long rekey_time);
  112. static SeatPromptResult ssh2_transport_confirm_weak_crypto_primitive(
  113. struct ssh2_transport_state *s, const char *type, const char *name,
  114. const void *alg, WeakCryptoReason wcr);
  115. static const char *const kexlist_descr[NKEXLIST] = {
  116. "key exchange algorithm",
  117. "host key algorithm",
  118. "client-to-server cipher",
  119. "server-to-client cipher",
  120. "client-to-server MAC",
  121. "server-to-client MAC",
  122. "client-to-server compression method",
  123. "server-to-client compression method"
  124. };
  125. static int weak_algorithm_compare(void *av, void *bv);
  126. static int ca_blob_compare(void *av, void *bv);
  127. PacketProtocolLayer *ssh2_transport_new(
  128. Conf *conf, const char *host, int port, const char *fullhostname,
  129. const char *client_greeting, const char *server_greeting,
  130. struct ssh_connection_shared_gss_state *shgss,
  131. struct DataTransferStats *stats, PacketProtocolLayer *higher_layer,
  132. const SshServerConfig *ssc)
  133. {
  134. struct ssh2_transport_state *s = snew(struct ssh2_transport_state);
  135. memset(s, 0, sizeof(*s));
  136. s->ppl.vt = &ssh2_transport_vtable;
  137. s->conf = conf_copy(conf);
  138. s->savedhost = dupstr(host);
  139. s->savedport = port;
  140. s->fullhostname = dupstr(fullhostname);
  141. s->shgss = shgss;
  142. s->client_greeting = dupstr(client_greeting);
  143. s->server_greeting = dupstr(server_greeting);
  144. s->stats = stats;
  145. s->hostkeyblob = strbuf_new();
  146. s->host_cas = newtree234(ca_blob_compare);
  147. pq_in_init(&s->pq_in_higher, higher_layer->seat); // WINSCP
  148. pq_out_init(&s->pq_out_higher, higher_layer->seat); // WINSCP
  149. s->pq_out_higher.pqb.ic = &s->ic_pq_out_higher;
  150. s->ic_pq_out_higher.fn = ssh2_transport_higher_layer_packet_callback;
  151. s->ic_pq_out_higher.ctx = &s->ppl;
  152. s->ic_pq_out_higher.set = get_seat_callback_set(higher_layer->seat);
  153. s->higher_layer = higher_layer;
  154. s->higher_layer->selfptr = &s->higher_layer;
  155. ssh_ppl_setup_queues(s->higher_layer, &s->pq_in_higher, &s->pq_out_higher);
  156. #ifndef NO_GSSAPI
  157. s->gss_cred_expiry = GSS_NO_EXPIRATION;
  158. s->shgss->srv_name = GSS_C_NO_NAME;
  159. s->shgss->ctx = NULL;
  160. #endif
  161. s->thc = ssh_transient_hostkey_cache_new();
  162. s->gss_kex_used = false;
  163. s->outgoing_kexinit = strbuf_new();
  164. s->incoming_kexinit = strbuf_new();
  165. if (ssc) {
  166. s->ssc = ssc;
  167. s->client_kexinit = s->incoming_kexinit;
  168. s->server_kexinit = s->outgoing_kexinit;
  169. s->cstrans = &s->in;
  170. s->sctrans = &s->out;
  171. s->out.mkkey_adjust = 1;
  172. } else {
  173. s->client_kexinit = s->outgoing_kexinit;
  174. s->server_kexinit = s->incoming_kexinit;
  175. s->cstrans = &s->out;
  176. s->sctrans = &s->in;
  177. s->in.mkkey_adjust = 1;
  178. }
  179. s->weak_algorithms_consented_to = newtree234(weak_algorithm_compare);
  180. ssh2_transport_set_max_data_size(s);
  181. return &s->ppl;
  182. }
  183. static void ssh2_transport_free(PacketProtocolLayer *ppl)
  184. {
  185. struct ssh2_transport_state *s =
  186. container_of(ppl, struct ssh2_transport_state, ppl);
  187. /*
  188. * As our last act before being freed, move any outgoing packets
  189. * off our higher layer's output queue on to our own output queue.
  190. * We might be being freed while the SSH connection is still alive
  191. * (because we're initiating shutdown from our end), in which case
  192. * we don't want those last few packets to get lost.
  193. *
  194. * (If our owner were to have already destroyed our output pq
  195. * before wanting to free us, then it would have to reset our
  196. * publicly visible out_pq field to NULL to inhibit this attempt.
  197. * But that's not how I expect the shutdown sequence to go in
  198. * practice.)
  199. */
  200. if (s->ppl.out_pq)
  201. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  202. conf_free(s->conf);
  203. ssh_ppl_free(s->higher_layer);
  204. pq_in_clear(&s->pq_in_higher);
  205. pq_out_clear(&s->pq_out_higher);
  206. sfree(s->savedhost);
  207. sfree(s->fullhostname);
  208. sfree(s->client_greeting);
  209. sfree(s->server_greeting);
  210. sfree(s->keystr);
  211. strbuf_free(s->hostkeyblob);
  212. {
  213. host_ca *hca;
  214. while ( (hca = delpos234(s->host_cas, 0)) )
  215. host_ca_free(hca);
  216. freetree234(s->host_cas);
  217. }
  218. if (s->hkey && !s->hostkeys) {
  219. ssh_key_free(s->hkey);
  220. s->hkey = NULL;
  221. }
  222. { // WINSCP
  223. size_t i;
  224. for (i = 0; i < NKEXLIST; i++)
  225. sfree(s->kexlists[i].algs);
  226. if (s->f) mp_free(s->f);
  227. if (s->p) mp_free(s->p);
  228. if (s->g) mp_free(s->g);
  229. if (s->ebuf) strbuf_free(s->ebuf);
  230. if (s->fbuf) strbuf_free(s->fbuf);
  231. if (s->kex_shared_secret) strbuf_free(s->kex_shared_secret);
  232. if (s->dh_ctx)
  233. dh_cleanup(s->dh_ctx);
  234. if (s->rsa_kex_key_needs_freeing) {
  235. ssh_rsakex_freekey(s->rsa_kex_key);
  236. sfree(s->rsa_kex_key);
  237. }
  238. if (s->ecdh_key)
  239. ecdh_key_free(s->ecdh_key);
  240. if (s->exhash)
  241. ssh_hash_free(s->exhash);
  242. strbuf_free(s->outgoing_kexinit);
  243. strbuf_free(s->incoming_kexinit);
  244. ssh_transient_hostkey_cache_free(s->thc);
  245. freetree234(s->weak_algorithms_consented_to);
  246. expire_timer_context(s);
  247. sfree(s);
  248. } // WINSCP
  249. }
  250. /*
  251. * SSH-2 key derivation (RFC 4253 section 7.2).
  252. */
  253. static void ssh2_mkkey(
  254. struct ssh2_transport_state *s, strbuf *out,
  255. strbuf *kex_shared_secret, unsigned char *H, char chr, int keylen)
  256. {
  257. int hlen = s->kex_alg->hash->hlen;
  258. int keylen_padded;
  259. unsigned char *key;
  260. ssh_hash *h;
  261. if (keylen == 0)
  262. return;
  263. /*
  264. * Round the requested amount of key material up to a multiple of
  265. * the length of the hash we're using to make it. This makes life
  266. * simpler because then we can just write each hash output block
  267. * straight into the output buffer without fiddling about
  268. * truncating the last one. Since it's going into a strbuf, and
  269. * strbufs are always smemclr()ed on free, there's no need to
  270. * worry about leaving extra potentially-sensitive data in memory
  271. * that the caller didn't ask for.
  272. */
  273. keylen_padded = ((keylen + hlen - 1) / hlen) * hlen;
  274. strbuf_clear(out);
  275. key = strbuf_append(out, keylen_padded);
  276. /* First hlen bytes. */
  277. h = ssh_hash_new(s->kex_alg->hash);
  278. if (!(s->ppl.remote_bugs & BUG_SSH2_DERIVEKEY))
  279. put_datapl(h, ptrlen_from_strbuf(kex_shared_secret));
  280. put_data(h, H, hlen);
  281. put_byte(h, chr);
  282. put_data(h, s->session_id, s->session_id_len);
  283. ssh_hash_digest(h, key);
  284. /* Subsequent blocks of hlen bytes. */
  285. if (keylen_padded > hlen) {
  286. int offset;
  287. ssh_hash_reset(h);
  288. if (!(s->ppl.remote_bugs & BUG_SSH2_DERIVEKEY))
  289. put_datapl(h, ptrlen_from_strbuf(kex_shared_secret));
  290. put_data(h, H, hlen);
  291. for (offset = hlen; offset < keylen_padded; offset += hlen) {
  292. put_data(h, key + offset - hlen, hlen);
  293. ssh_hash_digest_nondestructive(h, key + offset);
  294. }
  295. }
  296. ssh_hash_free(h);
  297. }
  298. /*
  299. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  300. * If the algorithm is already in the list, return a pointer to its
  301. * entry, otherwise return an entry from the end of the list.
  302. *
  303. * 'name' is expected to be a ptrlen which it's safe to keep a copy
  304. * of.
  305. */
  306. static struct kexinit_algorithm *ssh2_kexinit_addalg_pl(
  307. struct kexinit_algorithm_list *list, ptrlen name)
  308. {
  309. size_t i; // WINSCP
  310. for (i = 0; i < list->nalgs; i++)
  311. if (ptrlen_eq_ptrlen(list->algs[i].name, name))
  312. return &list->algs[i];
  313. sgrowarray(list->algs, list->algsize, list->nalgs);
  314. { // WINSCP
  315. struct kexinit_algorithm *entry = &list->algs[list->nalgs++];
  316. entry->name = name;
  317. return entry;
  318. } // WINSCP
  319. }
  320. static struct kexinit_algorithm *ssh2_kexinit_addalg(
  321. struct kexinit_algorithm_list *list, const char *name)
  322. {
  323. return ssh2_kexinit_addalg_pl(list, ptrlen_from_asciz(name));
  324. }
  325. bool ssh2_common_filter_queue(PacketProtocolLayer *ppl)
  326. {
  327. static const char *const ssh2_disconnect_reasons[] = {
  328. NULL,
  329. "host not allowed to connect",
  330. "protocol error",
  331. "key exchange failed",
  332. "host authentication failed",
  333. "MAC error",
  334. "compression error",
  335. "service not available",
  336. "protocol version not supported",
  337. "host key not verifiable",
  338. "connection lost",
  339. "by application",
  340. "too many connections",
  341. "auth cancelled by user",
  342. "no more auth methods available",
  343. "illegal user name",
  344. };
  345. PktIn *pktin;
  346. ptrlen msg;
  347. int reason;
  348. while ((pktin = pq_peek(ppl->in_pq)) != NULL) {
  349. switch (pktin->type) {
  350. case SSH2_MSG_DISCONNECT:
  351. reason = get_uint32(pktin);
  352. msg = get_string(pktin);
  353. ssh_remote_error(
  354. ppl->ssh, "Remote side sent disconnect message\n"
  355. "type %d (%s):\n\"%.*s\"", reason,
  356. ((reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  357. ssh2_disconnect_reasons[reason] : "unknown"),
  358. PTRLEN_PRINTF(msg));
  359. /* don't try to pop the queue, because we've been freed! */
  360. return true; /* indicate that we've been freed */
  361. case SSH2_MSG_DEBUG:
  362. /* XXX maybe we should actually take notice of the return value */
  363. get_bool(pktin);
  364. msg = get_string(pktin);
  365. ppl_logevent("Remote debug message: %.*s", PTRLEN_PRINTF(msg));
  366. pq_pop(ppl->in_pq);
  367. break;
  368. case SSH2_MSG_IGNORE:
  369. /* Do nothing, because we're ignoring it! Duhh. */
  370. pq_pop(ppl->in_pq);
  371. break;
  372. case SSH2_MSG_EXT_INFO: {
  373. /*
  374. * The BPP enforces that these turn up only at legal
  375. * points in the protocol. In particular, it will not pass
  376. * an EXT_INFO on to us if it arrives before encryption is
  377. * enabled (which is when a MITM could inject one
  378. * maliciously).
  379. *
  380. * However, one of the criteria for legality is that a
  381. * server is permitted to send this message immediately
  382. * _before_ USERAUTH_SUCCESS. So we may receive this
  383. * message not yet knowing whether it's legal to have sent
  384. * it - we won't know until the BPP processes the next
  385. * packet.
  386. *
  387. * But that should be OK, because firstly, an
  388. * out-of-sequence EXT_INFO that's still within the
  389. * encrypted session is only a _protocol_ violation, not
  390. * an attack; secondly, any data we set in response to
  391. * such an illegal EXT_INFO won't have a chance to affect
  392. * the session before the BPP aborts it anyway.
  393. */
  394. uint32_t nexts = get_uint32(pktin);
  395. uint32_t i; // WINSCP
  396. for (i = 0; i < nexts && !get_err(pktin); i++) {
  397. ptrlen extname = get_string(pktin);
  398. ptrlen extvalue = get_string(pktin);
  399. if (ptrlen_eq_string(extname, "server-sig-algs")) {
  400. /*
  401. * Server has sent a list of signature algorithms
  402. * it will potentially accept for user
  403. * authentication keys. Check in particular
  404. * whether the RFC 8332 improved versions of
  405. * ssh-rsa are in the list, and set flags in the
  406. * BPP if so.
  407. *
  408. * TODO: another thing we _could_ do here is to
  409. * record a full list of the algorithm identifiers
  410. * we've seen, whether we understand them
  411. * ourselves or not. Then we could use that as a
  412. * pre-filter during userauth, to skip keys in the
  413. * SSH agent if we already know the server can't
  414. * possibly accept them. (Even if the key
  415. * algorithm is one that the agent and the server
  416. * both understand but we do not.)
  417. */
  418. ptrlen algname;
  419. while (get_commasep_word(&extvalue, &algname)) {
  420. if (ptrlen_eq_string(algname, "rsa-sha2-256"))
  421. ppl->bpp->ext_info_rsa_sha256_ok = true;
  422. if (ptrlen_eq_string(algname, "rsa-sha2-512"))
  423. ppl->bpp->ext_info_rsa_sha512_ok = true;
  424. }
  425. }
  426. }
  427. pq_pop(ppl->in_pq);
  428. break;
  429. }
  430. default:
  431. return false;
  432. }
  433. }
  434. return false;
  435. }
  436. static bool ssh2_transport_filter_queue(struct ssh2_transport_state *s)
  437. {
  438. PktIn *pktin;
  439. if (!s->enabled_incoming_crypto) {
  440. /*
  441. * Record the fact that we've seen any non-KEXINIT packet at
  442. * the head of our queue.
  443. *
  444. * This enables us to check later that the initial incoming
  445. * KEXINIT was the very first packet, if scanning the KEXINITs
  446. * turns out to enable strict-kex mode.
  447. */
  448. PktIn *pktin = pq_peek(s->ppl.in_pq);
  449. if (pktin && pktin->type != SSH2_MSG_KEXINIT)
  450. s->seen_non_kexinit = true;
  451. if (s->strict_kex) {
  452. /*
  453. * Also, if we're already in strict-KEX mode and haven't
  454. * turned on crypto yet, don't do any actual filtering.
  455. * This ensures that extraneous packets _after_ the
  456. * KEXINIT will go to the main coroutine, which will
  457. * complain about them.
  458. */
  459. return false;
  460. }
  461. }
  462. while (1) {
  463. if (ssh2_common_filter_queue(&s->ppl))
  464. return true;
  465. if ((pktin = pq_peek(s->ppl.in_pq)) == NULL)
  466. return false;
  467. /* Pass on packets to the next layer if they're outside
  468. * the range reserved for the transport protocol. */
  469. if (pktin->type >= 50) {
  470. /* ... except that we shouldn't tolerate higher-layer
  471. * packets coming from the server before we've seen
  472. * the first NEWKEYS. */
  473. if (!s->higher_layer_ok) {
  474. ssh_proto_error(s->ppl.ssh, "Received premature higher-"
  475. "layer packet, type %d (%s)", pktin->type,
  476. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  477. s->ppl.bpp->pls->actx,
  478. pktin->type));
  479. return true;
  480. }
  481. pq_pop(s->ppl.in_pq);
  482. pq_push(&s->pq_in_higher, pktin);
  483. } else {
  484. /* Anything else is a transport-layer packet that the main
  485. * process_queue coroutine should handle. */
  486. return false;
  487. }
  488. }
  489. }
  490. PktIn *ssh2_transport_pop(struct ssh2_transport_state *s)
  491. {
  492. if (ssh2_transport_filter_queue(s))
  493. return NULL; /* we've been freed */
  494. return pq_pop(s->ppl.in_pq);
  495. }
  496. static void ssh2_write_kexinit_lists(
  497. /*WINSCP*/ Seat * seat, BinarySink *pktout,
  498. struct kexinit_algorithm_list kexlists[NKEXLIST],
  499. Conf *conf, const SshServerConfig *ssc, int remote_bugs,
  500. const char *hk_host, int hk_port, const ssh_keyalg *hk_prev,
  501. ssh_transient_hostkey_cache *thc, tree234 *host_cas,
  502. ssh_key *const *our_hostkeys, int our_nhostkeys,
  503. bool first_time, bool can_gssapi_keyex, bool transient_hostkey_mode)
  504. {
  505. int i, j, k;
  506. bool warn;
  507. int n_preferred_kex;
  508. const ssh_kexes *preferred_kex[KEX_MAX + 3]; /* +3 for GSSAPI */
  509. int n_preferred_hk;
  510. int preferred_hk[HK_MAX];
  511. int n_preferred_ciphers;
  512. const ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  513. const ssh_compression_alg *preferred_comp;
  514. const ssh2_macalg *const *maclist;
  515. int nmacs;
  516. struct kexinit_algorithm *alg;
  517. /*
  518. * Set up the preferred key exchange. (NULL => warn below here)
  519. */
  520. n_preferred_kex = 0;
  521. if (can_gssapi_keyex) {
  522. preferred_kex[n_preferred_kex++] = &ssh_gssk5_ecdh_kex;
  523. preferred_kex[n_preferred_kex++] = &ssh_gssk5_sha2_kex;
  524. preferred_kex[n_preferred_kex++] = &ssh_gssk5_sha1_kex;
  525. }
  526. for (i = 0; i < KEX_MAX; i++) {
  527. switch (conf_get_int_int(conf, CONF_ssh_kexlist, i)) {
  528. case KEX_DHGEX:
  529. preferred_kex[n_preferred_kex++] =
  530. &ssh_diffiehellman_gex;
  531. break;
  532. case KEX_DHGROUP18:
  533. preferred_kex[n_preferred_kex++] =
  534. &ssh_diffiehellman_group18;
  535. break;
  536. case KEX_DHGROUP17:
  537. preferred_kex[n_preferred_kex++] =
  538. &ssh_diffiehellman_group17;
  539. break;
  540. case KEX_DHGROUP16:
  541. preferred_kex[n_preferred_kex++] =
  542. &ssh_diffiehellman_group16;
  543. break;
  544. case KEX_DHGROUP15:
  545. preferred_kex[n_preferred_kex++] =
  546. &ssh_diffiehellman_group15;
  547. break;
  548. case KEX_DHGROUP14:
  549. preferred_kex[n_preferred_kex++] =
  550. &ssh_diffiehellman_group14;
  551. break;
  552. case KEX_DHGROUP1:
  553. preferred_kex[n_preferred_kex++] =
  554. &ssh_diffiehellman_group1;
  555. break;
  556. case KEX_RSA:
  557. preferred_kex[n_preferred_kex++] =
  558. &ssh_rsa_kex;
  559. break;
  560. case KEX_ECDH:
  561. preferred_kex[n_preferred_kex++] =
  562. &ssh_ecdh_kex;
  563. break;
  564. case KEX_NTRU_HYBRID:
  565. preferred_kex[n_preferred_kex++] =
  566. &ssh_ntru_hybrid_kex;
  567. break;
  568. case KEX_WARN:
  569. /* Flag for later. Don't bother if it's the last in
  570. * the list. */
  571. if (i < KEX_MAX - 1) {
  572. preferred_kex[n_preferred_kex++] = NULL;
  573. }
  574. break;
  575. }
  576. }
  577. /*
  578. * Set up the preferred host key types. These are just the ids
  579. * in the enum in putty.h, so 'warn below here' is indicated
  580. * by HK_WARN.
  581. */
  582. n_preferred_hk = 0;
  583. for (i = 0; i < HK_MAX; i++) {
  584. int id = conf_get_int_int(conf, CONF_ssh_hklist, i);
  585. /* As above, don't bother with HK_WARN if it's last in the
  586. * list */
  587. if (id != HK_WARN || i < HK_MAX - 1)
  588. preferred_hk[n_preferred_hk++] = id;
  589. }
  590. /*
  591. * Set up the preferred ciphers. (NULL => warn below here)
  592. */
  593. n_preferred_ciphers = 0;
  594. for (i = 0; i < CIPHER_MAX; i++) {
  595. switch (conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  596. case CIPHER_BLOWFISH:
  597. preferred_ciphers[n_preferred_ciphers++] = &ssh2_blowfish;
  598. break;
  599. case CIPHER_DES:
  600. if (conf_get_bool(conf, CONF_ssh2_des_cbc))
  601. preferred_ciphers[n_preferred_ciphers++] = &ssh2_des;
  602. break;
  603. case CIPHER_3DES:
  604. preferred_ciphers[n_preferred_ciphers++] = &ssh2_3des;
  605. break;
  606. case CIPHER_AES:
  607. preferred_ciphers[n_preferred_ciphers++] = &ssh2_aes;
  608. break;
  609. case CIPHER_ARCFOUR:
  610. preferred_ciphers[n_preferred_ciphers++] = &ssh2_arcfour;
  611. break;
  612. case CIPHER_CHACHA20:
  613. preferred_ciphers[n_preferred_ciphers++] = &ssh2_ccp;
  614. break;
  615. case CIPHER_AESGCM:
  616. preferred_ciphers[n_preferred_ciphers++] = &ssh2_aesgcm;
  617. break;
  618. case CIPHER_WARN:
  619. /* Flag for later. Don't bother if it's the last in
  620. * the list. */
  621. if (i < CIPHER_MAX - 1) {
  622. preferred_ciphers[n_preferred_ciphers++] = NULL;
  623. }
  624. break;
  625. }
  626. }
  627. /*
  628. * Set up preferred compression.
  629. */
  630. if (conf_get_bool(conf, CONF_compression))
  631. preferred_comp = &ssh_zlib;
  632. else
  633. preferred_comp = &ssh_comp_none;
  634. for (i = 0; i < NKEXLIST; i++)
  635. kexlists[i].nalgs = 0;
  636. /* List key exchange algorithms. */
  637. warn = false;
  638. for (i = 0; i < n_preferred_kex; i++) {
  639. const ssh_kexes *k = preferred_kex[i];
  640. if (!k) warn = true;
  641. else for (j = 0; j < k->nkexes; j++) {
  642. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_KEX],
  643. k->list[j]->name);
  644. alg->u.kex.kex = k->list[j];
  645. alg->u.kex.warn = warn;
  646. }
  647. }
  648. /* List server host key algorithms. */
  649. if (our_hostkeys) {
  650. /*
  651. * In server mode, we just list the algorithms that match the
  652. * host keys we actually have.
  653. */
  654. for (i = 0; i < our_nhostkeys; i++) {
  655. const ssh_keyalg *keyalg = ssh_key_alg(our_hostkeys[i]);
  656. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY],
  657. keyalg->ssh_id);
  658. alg->u.hk.hostkey = keyalg;
  659. alg->u.hk.hkflags = 0;
  660. alg->u.hk.warn = false;
  661. { // WINSCP
  662. uint32_t supported_flags = ssh_keyalg_supported_flags(keyalg);
  663. static const uint32_t try_flags[] = {
  664. SSH_AGENT_RSA_SHA2_256,
  665. SSH_AGENT_RSA_SHA2_512,
  666. };
  667. { // WINSCP
  668. size_t i;
  669. for (i = 0; i < lenof(try_flags); i++) {
  670. if (try_flags[i] & ~supported_flags)
  671. continue; /* these flags not supported */
  672. alg = ssh2_kexinit_addalg(
  673. &kexlists[KEXLIST_HOSTKEY],
  674. ssh_keyalg_alternate_ssh_id(keyalg, try_flags[i]));
  675. alg->u.hk.hostkey = keyalg;
  676. alg->u.hk.hkflags = try_flags[i];
  677. alg->u.hk.warn = false;
  678. }
  679. } // WINSCP
  680. } // WINSCP
  681. }
  682. } else if (first_time) {
  683. /*
  684. * In the first key exchange, we list all the algorithms we're
  685. * prepared to cope with, but (if configured to) we prefer
  686. * those algorithms for which we have a host key for this
  687. * host.
  688. *
  689. * If the host key algorithm is below the warning
  690. * threshold, we warn even if we did already have a key
  691. * for it, on the basis that if the user has just
  692. * reconfigured that host key type to be warned about,
  693. * they surely _do_ want to be alerted that a server
  694. * they're actually connecting to is using it.
  695. */
  696. bool accept_certs = false;
  697. {
  698. host_ca_enum *handle = enum_host_ca_start();
  699. if (handle) {
  700. strbuf *name = strbuf_new();
  701. while (strbuf_clear(name), enum_host_ca_next(handle, name)) {
  702. host_ca *hca = host_ca_load(name->s);
  703. if (!hca)
  704. continue;
  705. if (hca->ca_public_key &&
  706. cert_expr_match_str(hca->validity_expression,
  707. hk_host, hk_port)) {
  708. accept_certs = true;
  709. add234(host_cas, hca);
  710. } else {
  711. host_ca_free(hca);
  712. }
  713. }
  714. enum_host_ca_finish(handle);
  715. strbuf_free(name);
  716. }
  717. }
  718. if (accept_certs) {
  719. /* Add all the certificate algorithms first, in preference order */
  720. warn = false;
  721. for (i = 0; i < n_preferred_hk; i++) {
  722. if (preferred_hk[i] == HK_WARN)
  723. warn = true;
  724. for (j = 0; j < lenof(ssh2_hostkey_algs); j++) {
  725. const struct ssh_signkey_with_user_pref_id *a =
  726. &ssh2_hostkey_algs[j];
  727. if (!a->alg->is_certificate)
  728. continue;
  729. if (a->id != preferred_hk[i])
  730. continue;
  731. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY],
  732. a->alg->ssh_id);
  733. alg->u.hk.hostkey = a->alg;
  734. alg->u.hk.warn = warn;
  735. }
  736. }
  737. }
  738. /* Next, add algorithms we already know a key for (unless
  739. * configured not to do that) */
  740. warn = false;
  741. for (i = 0; i < n_preferred_hk; i++) {
  742. if (preferred_hk[i] == HK_WARN)
  743. warn = true;
  744. for (j = 0; j < lenof(ssh2_hostkey_algs); j++) {
  745. const struct ssh_signkey_with_user_pref_id *a =
  746. &ssh2_hostkey_algs[j];
  747. if (a->alg->is_certificate && accept_certs)
  748. continue; /* already added this one */
  749. if (a->id != preferred_hk[i])
  750. continue;
  751. if (conf_get_bool(conf, CONF_ssh_prefer_known_hostkeys) &&
  752. have_ssh_host_key(seat, hk_host, hk_port, // WINSCP
  753. a->alg->cache_id)) {
  754. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY],
  755. a->alg->ssh_id);
  756. alg->u.hk.hostkey = a->alg;
  757. alg->u.hk.warn = warn;
  758. }
  759. }
  760. }
  761. /* And finally, everything else */
  762. warn = false;
  763. for (i = 0; i < n_preferred_hk; i++) {
  764. if (preferred_hk[i] == HK_WARN)
  765. warn = true;
  766. for (j = 0; j < lenof(ssh2_hostkey_algs); j++) {
  767. const struct ssh_signkey_with_user_pref_id *a =
  768. &ssh2_hostkey_algs[j];
  769. if (a->alg->is_certificate)
  770. continue;
  771. if (a->id != preferred_hk[i])
  772. continue;
  773. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY],
  774. a->alg->ssh_id);
  775. alg->u.hk.hostkey = a->alg;
  776. alg->u.hk.warn = warn;
  777. }
  778. }
  779. #ifndef NO_GSSAPI
  780. } else if (transient_hostkey_mode) {
  781. /*
  782. * If we've previously done a GSSAPI KEX, then we list
  783. * precisely the algorithms for which a previous GSS key
  784. * exchange has delivered us a host key, because we expect
  785. * one of exactly those keys to be used in any subsequent
  786. * non-GSS-based rekey.
  787. *
  788. * An exception is if this is the key exchange we
  789. * triggered for the purposes of populating that cache -
  790. * in which case the cache will currently be empty, which
  791. * isn't helpful!
  792. */
  793. warn = false;
  794. for (i = 0; i < n_preferred_hk; i++) {
  795. if (preferred_hk[i] == HK_WARN)
  796. warn = true;
  797. for (j = 0; j < lenof(ssh2_hostkey_algs); j++) {
  798. if (ssh2_hostkey_algs[j].id != preferred_hk[i])
  799. continue;
  800. if (ssh_transient_hostkey_cache_has(
  801. thc, ssh2_hostkey_algs[j].alg)) {
  802. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY],
  803. ssh2_hostkey_algs[j].alg->ssh_id);
  804. alg->u.hk.hostkey = ssh2_hostkey_algs[j].alg;
  805. alg->u.hk.warn = warn;
  806. }
  807. }
  808. }
  809. #endif
  810. } else {
  811. /*
  812. * In subsequent key exchanges, we list only the host key
  813. * algorithm that was selected in the first key exchange,
  814. * so that we keep getting the same host key and hence
  815. * don't have to interrupt the user's session to ask for
  816. * reverification.
  817. */
  818. assert(hk_prev);
  819. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY], hk_prev->ssh_id);
  820. alg->u.hk.hostkey = hk_prev;
  821. alg->u.hk.warn = false;
  822. }
  823. if (can_gssapi_keyex) {
  824. alg = ssh2_kexinit_addalg(&kexlists[KEXLIST_HOSTKEY], "null");
  825. alg->u.hk.hostkey = NULL;
  826. }
  827. /* List encryption algorithms (client->server then server->client). */
  828. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  829. warn = false;
  830. #ifdef FUZZING
  831. alg = ssh2_kexinit_addalg(&kexlists[K], "none");
  832. alg->u.cipher.cipher = NULL;
  833. alg->u.cipher.warn = warn;
  834. #endif /* FUZZING */
  835. for (i = 0; i < n_preferred_ciphers; i++) {
  836. const ssh2_ciphers *c = preferred_ciphers[i];
  837. if (!c) warn = true;
  838. else for (j = 0; j < c->nciphers; j++) {
  839. alg = ssh2_kexinit_addalg(&kexlists[k],
  840. c->list[j]->ssh2_id);
  841. alg->u.cipher.cipher = c->list[j];
  842. alg->u.cipher.warn = warn;
  843. }
  844. }
  845. }
  846. /*
  847. * Be prepared to work around the buggy MAC problem.
  848. */
  849. if (remote_bugs & BUG_SSH2_HMAC) {
  850. maclist = buggymacs;
  851. nmacs = lenof(buggymacs);
  852. } else {
  853. maclist = macs;
  854. nmacs = lenof(macs);
  855. }
  856. /* List MAC algorithms (client->server then server->client). */
  857. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  858. #ifdef FUZZING
  859. alg = ssh2_kexinit_addalg(kexlists[j], "none");
  860. alg->u.mac.mac = NULL;
  861. alg->u.mac.etm = false;
  862. #endif /* FUZZING */
  863. for (i = 0; i < nmacs; i++) {
  864. alg = ssh2_kexinit_addalg(&kexlists[j], maclist[i]->name);
  865. alg->u.mac.mac = maclist[i];
  866. alg->u.mac.etm = false;
  867. }
  868. for (i = 0; i < nmacs; i++) {
  869. /* For each MAC, there may also be an ETM version,
  870. * which we list second. */
  871. if (maclist[i]->etm_name) {
  872. alg = ssh2_kexinit_addalg(&kexlists[j], maclist[i]->etm_name);
  873. alg->u.mac.mac = maclist[i];
  874. alg->u.mac.etm = true;
  875. }
  876. }
  877. }
  878. /* List client->server compression algorithms,
  879. * then server->client compression algorithms. (We use the
  880. * same set twice.) */
  881. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  882. assert(lenof(compressions) > 1);
  883. /* Prefer non-delayed versions */
  884. alg = ssh2_kexinit_addalg(&kexlists[j], preferred_comp->name);
  885. alg->u.comp.comp = preferred_comp;
  886. alg->u.comp.delayed = false;
  887. if (preferred_comp->delayed_name) {
  888. alg = ssh2_kexinit_addalg(&kexlists[j],
  889. preferred_comp->delayed_name);
  890. alg->u.comp.comp = preferred_comp;
  891. alg->u.comp.delayed = true;
  892. }
  893. for (i = 0; i < lenof(compressions); i++) {
  894. const ssh_compression_alg *c = compressions[i];
  895. alg = ssh2_kexinit_addalg(&kexlists[j], c->name);
  896. alg->u.comp.comp = c;
  897. alg->u.comp.delayed = false;
  898. if (c->delayed_name) {
  899. alg = ssh2_kexinit_addalg(&kexlists[j], c->delayed_name);
  900. alg->u.comp.comp = c;
  901. alg->u.comp.delayed = true;
  902. }
  903. }
  904. }
  905. /*
  906. * Finally, format the lists into text and write them into the
  907. * outgoing KEXINIT packet.
  908. */
  909. for (i = 0; i < NKEXLIST; i++) {
  910. strbuf *list = strbuf_new();
  911. #ifndef WINSCP
  912. if (ssc && ssc->kex_override[i].ptr) {
  913. put_datapl(list, ssc->kex_override[i]);
  914. } else {
  915. #endif
  916. for (j = 0; j < kexlists[i].nalgs; j++)
  917. add_to_commasep_pl(list, kexlists[i].algs[j].name);
  918. #ifndef WINSCP
  919. }
  920. #endif
  921. if (i == KEXLIST_KEX && first_time) {
  922. if (our_hostkeys) { /* we're the server */
  923. add_to_commasep_pl(list, ext_info_s);
  924. add_to_commasep_pl(list, kex_strict_s);
  925. } else { /* we're the client */
  926. add_to_commasep_pl(list, ext_info_c);
  927. add_to_commasep_pl(list, kex_strict_c);
  928. }
  929. }
  930. put_stringsb(pktout, list);
  931. }
  932. /* List client->server languages. Empty list. */
  933. put_stringz(pktout, "");
  934. /* List server->client languages. Empty list. */
  935. put_stringz(pktout, "");
  936. }
  937. struct server_hostkeys {
  938. int *indices;
  939. size_t n, size;
  940. };
  941. static bool kexinit_keyword_found(ptrlen list, ptrlen keyword)
  942. {
  943. ptrlen word; // WINSCP
  944. for (; get_commasep_word(&list, &word) ;)
  945. if (ptrlen_eq_ptrlen(word, keyword))
  946. return true;
  947. return false;
  948. }
  949. typedef struct ScanKexinitsResult {
  950. bool success;
  951. /* only if success is false */
  952. enum {
  953. SKR_INCOMPLETE,
  954. SKR_UNKNOWN_ID,
  955. SKR_NO_AGREEMENT,
  956. } error;
  957. const char *kind; /* what kind of thing did we fail to sort out? */
  958. ptrlen desc; /* and what was it? or what was the available list? */
  959. } ScanKexinitsResult;
  960. static ScanKexinitsResult ssh2_scan_kexinits(
  961. ptrlen client_kexinit, ptrlen server_kexinit, bool we_are_server,
  962. struct kexinit_algorithm_list kexlists[NKEXLIST],
  963. const ssh_kex **kex_alg, const ssh_keyalg **hostkey_alg,
  964. transport_direction *cs, transport_direction *sc,
  965. bool *warn_kex, bool *warn_hk, bool *warn_cscipher, bool *warn_sccipher,
  966. bool *ignore_guess_cs_packet, bool *ignore_guess_sc_packet,
  967. struct server_hostkeys *server_hostkeys, unsigned *hkflags,
  968. bool *can_send_ext_info, bool first_time, bool *strict_kex)
  969. {
  970. BinarySource client[1], server[1];
  971. int i;
  972. bool guess_correct;
  973. ptrlen clists[NKEXLIST], slists[NKEXLIST];
  974. const struct kexinit_algorithm *selected[NKEXLIST];
  975. BinarySource_BARE_INIT_PL(client, client_kexinit);
  976. BinarySource_BARE_INIT_PL(server, server_kexinit);
  977. /* Skip packet type bytes and random cookies. */
  978. get_data(client, 1 + 16);
  979. get_data(server, 1 + 16);
  980. guess_correct = true;
  981. /* Find the matching string in each list, and map it to its
  982. * kexinit_algorithm structure. */
  983. for (i = 0; i < NKEXLIST; i++) {
  984. ptrlen clist, slist, cword, sword, found;
  985. bool cfirst, sfirst;
  986. int j;
  987. clists[i] = get_string(client);
  988. slists[i] = get_string(server);
  989. if (get_err(client) || get_err(server)) {
  990. ScanKexinitsResult skr = {
  991. /*.success =*/ false, /*.error =*/ SKR_INCOMPLETE,
  992. };
  993. return skr;
  994. }
  995. for (cfirst = true, clist = clists[i];
  996. get_commasep_word(&clist, &cword); cfirst = false)
  997. for (sfirst = true, slist = slists[i];
  998. get_commasep_word(&slist, &sword); sfirst = false)
  999. if (ptrlen_eq_ptrlen(cword, sword)) {
  1000. found = cword;
  1001. goto found_match;
  1002. }
  1003. /* No matching string found in the two lists. Delay reporting
  1004. * a fatal error until below, because sometimes it turns out
  1005. * not to be fatal. */
  1006. selected[i] = NULL;
  1007. /*
  1008. * However, even if a failure to agree on any algorithm at all
  1009. * is not completely fatal (e.g. because it's the MAC
  1010. * negotiation for a cipher that comes with a built-in MAC),
  1011. * it still invalidates the guessed key exchange packet. (RFC
  1012. * 4253 section 7, not contradicted by OpenSSH's
  1013. * PROTOCOL.chacha20poly1305 or as far as I can see by their
  1014. * code.)
  1015. */
  1016. guess_correct = false;
  1017. continue;
  1018. found_match:
  1019. selected[i] = NULL;
  1020. for (j = 0; j < kexlists[i].nalgs; j++) {
  1021. if (ptrlen_eq_ptrlen(found, kexlists[i].algs[j].name)) {
  1022. selected[i] = &kexlists[i].algs[j];
  1023. break;
  1024. }
  1025. }
  1026. if (!selected[i]) {
  1027. /*
  1028. * In the client, this should never happen! But in the
  1029. * server, where we allow manual override on the command
  1030. * line of the exact KEXINIT strings, it can happen
  1031. * because the command line contained a typo. So we
  1032. * produce a reasonably useful message instead of an
  1033. * assertion failure.
  1034. */
  1035. ScanKexinitsResult skr;
  1036. skr.success = false, skr.error = SKR_UNKNOWN_ID,
  1037. skr.kind = kexlist_descr[i], skr.desc = found;
  1038. return skr;
  1039. }
  1040. /*
  1041. * If the kex or host key algorithm is not the first one in
  1042. * both sides' lists, that means the guessed key exchange
  1043. * packet (if any) is officially wrong.
  1044. */
  1045. if ((i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) && !(cfirst || sfirst))
  1046. guess_correct = false;
  1047. }
  1048. /*
  1049. * Skip language strings in both KEXINITs, and read the flags
  1050. * saying whether a guessed KEX packet follows.
  1051. */
  1052. get_string(client);
  1053. get_string(client);
  1054. get_string(server);
  1055. get_string(server);
  1056. if (ignore_guess_cs_packet)
  1057. *ignore_guess_cs_packet = get_bool(client) && !guess_correct;
  1058. if (ignore_guess_sc_packet)
  1059. *ignore_guess_sc_packet = get_bool(server) && !guess_correct;
  1060. /*
  1061. * Now transcribe the selected algorithm set into the output data.
  1062. */
  1063. for (i = 0; i < NKEXLIST; i++) {
  1064. const struct kexinit_algorithm *alg;
  1065. /*
  1066. * If we've already selected a cipher which requires a
  1067. * particular MAC, then just select that. This is the case in
  1068. * which it's not a fatal error if the actual MAC string lists
  1069. * didn't include any matching error.
  1070. */
  1071. if (i == KEXLIST_CSMAC && cs->cipher &&
  1072. cs->cipher->required_mac) {
  1073. cs->mac = cs->cipher->required_mac;
  1074. cs->etm_mode = !!(cs->mac->etm_name);
  1075. continue;
  1076. }
  1077. if (i == KEXLIST_SCMAC && sc->cipher &&
  1078. sc->cipher->required_mac) {
  1079. sc->mac = sc->cipher->required_mac;
  1080. sc->etm_mode = !!(sc->mac->etm_name);
  1081. continue;
  1082. }
  1083. alg = selected[i];
  1084. if (!alg) {
  1085. /*
  1086. * Otherwise, any match failure _is_ a fatal error.
  1087. */
  1088. ScanKexinitsResult skr;
  1089. skr.success = false, skr.error = SKR_UNKNOWN_ID,
  1090. skr.kind = kexlist_descr[i], skr.desc = slists[i];
  1091. return skr;
  1092. }
  1093. switch (i) {
  1094. case KEXLIST_KEX:
  1095. *kex_alg = alg->u.kex.kex;
  1096. *warn_kex = alg->u.kex.warn;
  1097. break;
  1098. case KEXLIST_HOSTKEY:
  1099. /*
  1100. * Ignore an unexpected/inappropriate offer of "null",
  1101. * we offer "null" when we're willing to use GSS KEX,
  1102. * but it is only acceptable when GSSKEX is actually
  1103. * selected.
  1104. */
  1105. if (alg->u.hk.hostkey == NULL &&
  1106. (*kex_alg)->main_type != KEXTYPE_GSS)
  1107. continue;
  1108. *hostkey_alg = alg->u.hk.hostkey;
  1109. *hkflags = alg->u.hk.hkflags;
  1110. *warn_hk = alg->u.hk.warn;
  1111. break;
  1112. case KEXLIST_CSCIPHER:
  1113. cs->cipher = alg->u.cipher.cipher;
  1114. *warn_cscipher = alg->u.cipher.warn;
  1115. break;
  1116. case KEXLIST_SCCIPHER:
  1117. sc->cipher = alg->u.cipher.cipher;
  1118. *warn_sccipher = alg->u.cipher.warn;
  1119. break;
  1120. case KEXLIST_CSMAC:
  1121. cs->mac = alg->u.mac.mac;
  1122. cs->etm_mode = alg->u.mac.etm;
  1123. break;
  1124. case KEXLIST_SCMAC:
  1125. sc->mac = alg->u.mac.mac;
  1126. sc->etm_mode = alg->u.mac.etm;
  1127. break;
  1128. case KEXLIST_CSCOMP:
  1129. cs->comp = alg->u.comp.comp;
  1130. cs->comp_delayed = alg->u.comp.delayed;
  1131. break;
  1132. case KEXLIST_SCCOMP:
  1133. sc->comp = alg->u.comp.comp;
  1134. sc->comp_delayed = alg->u.comp.delayed;
  1135. break;
  1136. default:
  1137. unreachable("Bad list index in scan_kexinits");
  1138. }
  1139. }
  1140. /*
  1141. * Check whether the other side advertised support for EXT_INFO.
  1142. */
  1143. if (kexinit_keyword_found(
  1144. we_are_server ? clists[KEXLIST_KEX] : slists[KEXLIST_KEX],
  1145. we_are_server ? ext_info_c : ext_info_s))
  1146. *can_send_ext_info = true;
  1147. /*
  1148. * Check whether the other side advertised support for kex-strict.
  1149. */
  1150. if (first_time && kexinit_keyword_found(
  1151. we_are_server ? clists[KEXLIST_KEX] : slists[KEXLIST_KEX],
  1152. we_are_server ? kex_strict_c : kex_strict_s))
  1153. *strict_kex = true;
  1154. if (server_hostkeys) {
  1155. /*
  1156. * Finally, make an auxiliary pass over the server's host key
  1157. * list to find all the host key algorithms offered by the
  1158. * server which we know about at all, whether we selected each
  1159. * one or not. We return these as a list of indices into the
  1160. * constant ssh2_hostkey_algs[] array.
  1161. */
  1162. { // WINSCP
  1163. ptrlen list = slists[KEXLIST_HOSTKEY];
  1164. ptrlen word; // WINSCP
  1165. for (; get_commasep_word(&list, &word) ;) {
  1166. for (i = 0; i < lenof(ssh2_hostkey_algs); i++)
  1167. if (ptrlen_eq_string(word, ssh2_hostkey_algs[i].alg->ssh_id)) {
  1168. sgrowarray(server_hostkeys->indices, server_hostkeys->size,
  1169. server_hostkeys->n);
  1170. server_hostkeys->indices[server_hostkeys->n++] = i;
  1171. break;
  1172. }
  1173. }
  1174. } // WINSCP
  1175. }
  1176. { // WINSCP
  1177. ScanKexinitsResult skr = { /*.success =*/ true };
  1178. return skr;
  1179. } // WINSCP
  1180. }
  1181. static void ssh2_report_scan_kexinits_error(Ssh *ssh, ScanKexinitsResult skr)
  1182. {
  1183. assert(!skr.success);
  1184. switch (skr.error) {
  1185. case SKR_INCOMPLETE:
  1186. /* Report a better error than the spurious "Couldn't
  1187. * agree" that we'd generate if we pressed on regardless
  1188. * and treated the empty get_string() result as genuine */
  1189. ssh_proto_error(ssh, "KEXINIT packet was incomplete");
  1190. break;
  1191. case SKR_UNKNOWN_ID:
  1192. ssh_sw_abort(ssh, "Selected %s \"%.*s\" does not correspond to "
  1193. "any supported algorithm",
  1194. skr.kind, PTRLEN_PRINTF(skr.desc));
  1195. break;
  1196. case SKR_NO_AGREEMENT:
  1197. ssh_sw_abort(ssh, "Couldn't agree a %s (available: %.*s)",
  1198. skr.kind, PTRLEN_PRINTF(skr.desc));
  1199. break;
  1200. default:
  1201. unreachable("bad ScanKexinitsResult");
  1202. }
  1203. }
  1204. static inline bool delay_outgoing_kexinit(struct ssh2_transport_state *s)
  1205. {
  1206. if (!(s->ppl.remote_bugs & BUG_REQUIRES_FILTERED_KEXINIT))
  1207. return false; /* bug flag not enabled => no need to delay */
  1208. if (s->incoming_kexinit->len)
  1209. return false; /* already got a remote KEXINIT we can filter against */
  1210. return true;
  1211. }
  1212. static void filter_outgoing_kexinit(struct ssh2_transport_state *s)
  1213. {
  1214. strbuf *pktout = strbuf_new();
  1215. BinarySource osrc[1], isrc[1];
  1216. BinarySource_BARE_INIT(
  1217. osrc, s->outgoing_kexinit->u, s->outgoing_kexinit->len);
  1218. BinarySource_BARE_INIT(
  1219. isrc, s->incoming_kexinit->u, s->incoming_kexinit->len);
  1220. /* Skip the packet type bytes from both packets */
  1221. get_byte(osrc);
  1222. get_byte(isrc);
  1223. /* Copy our cookie into the real output packet; skip their cookie */
  1224. put_datapl(pktout, get_data(osrc, 16));
  1225. get_data(isrc, 16);
  1226. /*
  1227. * Now we expect NKEXLIST+2 name-lists. We write into the outgoing
  1228. * packet a subset of our intended outgoing one, containing only
  1229. * names mentioned in the incoming out.
  1230. *
  1231. * NKEXLIST+2 because for this purpose we treat the 'languages'
  1232. * lists the same as the rest. In the rest of this code base we
  1233. * ignore those.
  1234. */
  1235. { // WINSCP
  1236. strbuf *out = strbuf_new();
  1237. size_t i; // WINSCP
  1238. for (i = 0; i < NKEXLIST+2; i++) {
  1239. strbuf_clear(out);
  1240. { // WINSCP
  1241. ptrlen olist = get_string(osrc), ilist = get_string(isrc);
  1242. ptrlen oword; // WINSCP
  1243. for (; get_commasep_word(&olist, &oword) ;) {
  1244. ptrlen searchword = oword;
  1245. ptrlen ilist_copy = ilist;
  1246. /*
  1247. * Special case: the kex_strict keywords are
  1248. * asymmetrically named, so if we're contemplating
  1249. * including one of them in our filtered KEXINIT, we
  1250. * should search the other side's KEXINIT for the _other_
  1251. * one, not the same one.
  1252. */
  1253. if (i == KEXLIST_KEX) {
  1254. if (ptrlen_eq_ptrlen(oword, kex_strict_c))
  1255. searchword = kex_strict_s;
  1256. else if (ptrlen_eq_ptrlen(oword, kex_strict_s))
  1257. searchword = kex_strict_c;
  1258. }
  1259. { // WINSCP
  1260. bool add = false;
  1261. ptrlen iword; // WINSCP
  1262. for (; get_commasep_word(&ilist_copy, &iword) ;) {
  1263. if (ptrlen_eq_ptrlen(searchword, iword)) {
  1264. /* Found this word in the incoming list. */
  1265. add = true;
  1266. break;
  1267. }
  1268. }
  1269. if (i == KEXLIST_KEX && ptrlen_eq_string(oword, "ext-info-c")) {
  1270. /* Special case: this will _never_ match anything from the
  1271. * server, and we need it to enable SHA-2 based RSA.
  1272. *
  1273. * If this ever turns out to confuse any server all by
  1274. * itself then I suppose we'll need an even more
  1275. * draconian bug flag to exclude that too. (Obv, such
  1276. * a server wouldn't be able to speak SHA-2 RSA
  1277. * anyway.) */
  1278. add = true;
  1279. }
  1280. if (add)
  1281. add_to_commasep_pl(out, oword);
  1282. } // WINSCP
  1283. }
  1284. put_stringpl(pktout, ptrlen_from_strbuf(out));
  1285. } // WINSCP
  1286. }
  1287. strbuf_free(out);
  1288. /*
  1289. * Finally, copy the remaining parts of our intended KEXINIT.
  1290. */
  1291. put_bool(pktout, get_bool(osrc)); /* first-kex-packet-follows */
  1292. put_uint32(pktout, get_uint32(osrc)); /* reserved word */
  1293. /*
  1294. * Dump this data into s->outgoing_kexinit in place of what we had
  1295. * there before. We need to remember the KEXINIT we _really_ sent,
  1296. * not the one we'd have liked to send, since the host key
  1297. * signature will be validated against the former.
  1298. */
  1299. strbuf_shrink_to(s->outgoing_kexinit, 1); /* keep the type byte */
  1300. put_datapl(s->outgoing_kexinit, ptrlen_from_strbuf(pktout));
  1301. strbuf_free(pktout);
  1302. } // WINSCP
  1303. }
  1304. void ssh2transport_finalise_exhash(struct ssh2_transport_state *s)
  1305. {
  1306. put_datapl(s->exhash, ptrlen_from_strbuf(s->kex_shared_secret));
  1307. assert(ssh_hash_alg(s->exhash)->hlen <= sizeof(s->exchange_hash));
  1308. ssh_hash_final(s->exhash, s->exchange_hash);
  1309. s->exhash = NULL;
  1310. #if 0
  1311. debug("Exchange hash is:\n");
  1312. dmemdump(s->exchange_hash, s->kex_alg->hash->hlen);
  1313. #endif
  1314. }
  1315. static void ssh2_transport_process_queue(PacketProtocolLayer *ppl)
  1316. {
  1317. struct ssh2_transport_state *s =
  1318. container_of(ppl, struct ssh2_transport_state, ppl);
  1319. PktIn *pktin;
  1320. PktOut *pktout;
  1321. /* Filter centrally handled messages off the front of the queue on
  1322. * every entry to this coroutine, no matter where we're resuming
  1323. * from, even if we're _not_ looping on pq_pop. That way we can
  1324. * still proactively handle those messages even if we're waiting
  1325. * for a user response. */
  1326. if (ssh2_transport_filter_queue(s))
  1327. return; /* we've been freed */
  1328. crBegin(s->crState);
  1329. s->in.cipher = s->out.cipher = NULL;
  1330. s->in.mac = s->out.mac = NULL;
  1331. s->in.comp = s->out.comp = NULL;
  1332. s->got_session_id = false;
  1333. s->need_gss_transient_hostkey = false;
  1334. s->warned_about_no_gss_transient_hostkey = false;
  1335. begin_key_exchange:
  1336. #ifndef NO_GSSAPI
  1337. if (s->need_gss_transient_hostkey) {
  1338. /*
  1339. * This flag indicates a special case in which we must not do
  1340. * GSS key exchange even if we could. (See comments below,
  1341. * where the flag was set on the previous key exchange.)
  1342. */
  1343. s->can_gssapi_keyex = false;
  1344. } else if (conf_get_bool(s->conf, CONF_try_gssapi_kex)) {
  1345. /*
  1346. * We always check if we have GSS creds before we come up with
  1347. * the kex algorithm list, otherwise future rekeys will fail
  1348. * when creds expire. To make this so, this code section must
  1349. * follow the begin_key_exchange label above, otherwise this
  1350. * section would execute just once per-connection.
  1351. *
  1352. * Update GSS state unless the reason we're here is that a
  1353. * timer just checked the GSS state and decided that we should
  1354. * rekey to update delegated credentials. In that case, the
  1355. * state is "fresh".
  1356. */
  1357. if (s->rekey_class != RK_GSS_UPDATE)
  1358. ssh2_transport_gss_update(s, true);
  1359. /* Do GSSAPI KEX when capable */
  1360. s->can_gssapi_keyex = s->gss_status & GSS_KEX_CAPABLE;
  1361. /*
  1362. * But not when failure is likely. [ GSS implementations may
  1363. * attempt (and fail) to use a ticket that is almost expired
  1364. * when retrieved from the ccache that actually expires by the
  1365. * time the server receives it. ]
  1366. *
  1367. * Note: The first time always try KEXGSS if we can, failures
  1368. * will be very rare, and disabling the initial GSS KEX is
  1369. * worse. Some day GSS libraries will ignore cached tickets
  1370. * whose lifetime is critically short, and will instead use
  1371. * fresh ones.
  1372. */
  1373. if (!s->got_session_id && (s->gss_status & GSS_CTXT_MAYFAIL) != 0)
  1374. s->can_gssapi_keyex = false;
  1375. s->gss_delegate = conf_get_bool(s->conf, CONF_gssapifwd);
  1376. } else {
  1377. s->can_gssapi_keyex = false;
  1378. }
  1379. #endif
  1380. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_NOKEX;
  1381. /*
  1382. * Construct our KEXINIT packet, in a strbuf so we can refer to it
  1383. * later.
  1384. */
  1385. strbuf_clear(s->outgoing_kexinit);
  1386. put_byte(s->outgoing_kexinit, SSH2_MSG_KEXINIT);
  1387. random_read(strbuf_append(s->outgoing_kexinit, 16), 16);
  1388. ssh2_write_kexinit_lists(
  1389. /*WINSCP*/ s->ppl.seat, BinarySink_UPCAST(s->outgoing_kexinit), s->kexlists,
  1390. s->conf, s->ssc, s->ppl.remote_bugs,
  1391. s->savedhost, s->savedport, s->hostkey_alg, s->thc, s->host_cas,
  1392. s->hostkeys, s->nhostkeys,
  1393. !s->got_session_id, s->can_gssapi_keyex,
  1394. s->gss_kex_used && !s->need_gss_transient_hostkey);
  1395. /* First KEX packet does _not_ follow, because we're not that brave. */
  1396. put_bool(s->outgoing_kexinit, false);
  1397. put_uint32(s->outgoing_kexinit, 0); /* reserved */
  1398. /*
  1399. * Send our KEXINIT, most of the time.
  1400. *
  1401. * An exception: in BUG_REQUIRES_FILTERED_KEXINIT mode, we have to
  1402. * have seen at least one KEXINIT from the server first, so that
  1403. * we can filter our own KEXINIT down to contain only algorithms
  1404. * the server mentioned.
  1405. *
  1406. * But we only need to do this on the _first_ key exchange, when
  1407. * we've never seen a KEXINIT from the server before. In rekeys,
  1408. * we still have the server's previous KEXINIT lying around, so we
  1409. * can filter based on that.
  1410. *
  1411. * (And a good thing too, since the way you _initiate_ a rekey is
  1412. * by sending your KEXINIT, so we'd have no way to prod the server
  1413. * into sending its first!)
  1414. */
  1415. s->kexinit_delayed = delay_outgoing_kexinit(s);
  1416. if (!s->kexinit_delayed) {
  1417. if (s->ppl.remote_bugs & BUG_REQUIRES_FILTERED_KEXINIT) {
  1418. /* Filter based on the KEXINIT from the previous exchange */
  1419. filter_outgoing_kexinit(s);
  1420. }
  1421. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEXINIT);
  1422. put_data(pktout, s->outgoing_kexinit->u + 1,
  1423. s->outgoing_kexinit->len - 1); /* omit type byte */
  1424. pq_push(s->ppl.out_pq, pktout);
  1425. }
  1426. /*
  1427. * Flag that KEX is in progress.
  1428. */
  1429. s->kex_in_progress = true;
  1430. /*
  1431. * Wait for the other side's KEXINIT, and save it.
  1432. */
  1433. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1434. if (pktin->type != SSH2_MSG_KEXINIT) {
  1435. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1436. "expecting KEXINIT, type %d (%s)", pktin->type,
  1437. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1438. s->ppl.bpp->pls->actx, pktin->type));
  1439. return;
  1440. }
  1441. strbuf_clear(s->incoming_kexinit);
  1442. put_byte(s->incoming_kexinit, SSH2_MSG_KEXINIT);
  1443. put_data(s->incoming_kexinit, get_ptr(pktin), get_avail(pktin));
  1444. /*
  1445. * If we've delayed sending our KEXINIT so as to filter it down to
  1446. * only things the server won't choke on, send ours now.
  1447. */
  1448. if (s->kexinit_delayed) {
  1449. filter_outgoing_kexinit(s);
  1450. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEXINIT);
  1451. put_data(pktout, s->outgoing_kexinit->u + 1,
  1452. s->outgoing_kexinit->len - 1); /* omit type byte */
  1453. pq_push(s->ppl.out_pq, pktout);
  1454. }
  1455. /*
  1456. * Work through the two KEXINIT packets in parallel to find the
  1457. * selected algorithm identifiers.
  1458. */
  1459. {
  1460. struct server_hostkeys hks = { NULL, 0, 0 };
  1461. ScanKexinitsResult skr = ssh2_scan_kexinits(
  1462. ptrlen_from_strbuf(s->client_kexinit),
  1463. ptrlen_from_strbuf(s->server_kexinit), s->ssc != NULL,
  1464. s->kexlists, &s->kex_alg, &s->hostkey_alg, s->cstrans,
  1465. s->sctrans, &s->warn_kex, &s->warn_hk, &s->warn_cscipher,
  1466. &s->warn_sccipher, NULL, &s->ignorepkt, &hks,
  1467. &s->hkflags, &s->can_send_ext_info, !s->got_session_id,
  1468. &s->strict_kex);
  1469. if (!skr.success) {
  1470. sfree(hks.indices);
  1471. ssh2_report_scan_kexinits_error(s->ppl.ssh, skr);
  1472. return; /* we just called a fatal error function */
  1473. }
  1474. /*
  1475. * If we've just turned on strict kex mode, say so, and
  1476. * retrospectively fault any pre-KEXINIT extraneous packets.
  1477. */
  1478. if (!s->got_session_id && s->strict_kex) {
  1479. ppl_logevent("Enabling strict key exchange semantics");
  1480. if (s->seen_non_kexinit) {
  1481. ssh_proto_error(s->ppl.ssh, "Received a packet before KEXINIT "
  1482. "in strict-kex mode");
  1483. return;
  1484. }
  1485. }
  1486. /*
  1487. * In addition to deciding which host key we're actually going
  1488. * to use, we should make a list of the host keys offered by
  1489. * the server which we _don't_ have cached. These will be
  1490. * offered as cross-certification options by ssh_get_specials.
  1491. *
  1492. * We also count the key we're currently using for KEX as one
  1493. * we've already got, because by the time this menu becomes
  1494. * visible, it will be.
  1495. */
  1496. s->n_uncert_hostkeys = 0;
  1497. { // WINSCP
  1498. int i;
  1499. for (i = 0; i < hks.n; i++) {
  1500. int j = hks.indices[i];
  1501. if (ssh2_hostkey_algs[j].alg != s->hostkey_alg &&
  1502. ssh2_hostkey_algs[j].alg->cache_id &&
  1503. !have_ssh_host_key(s->ppl.seat, s->savedhost, s->savedport, // WINSCP
  1504. ssh2_hostkey_algs[j].alg->cache_id)) {
  1505. s->uncert_hostkeys[s->n_uncert_hostkeys++] = j;
  1506. }
  1507. }
  1508. sfree(hks.indices);
  1509. } // WINSCP
  1510. }
  1511. if (s->warn_kex) {
  1512. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1513. s, "key-exchange algorithm", s->kex_alg->name, s->kex_alg,
  1514. WCR_BELOW_THRESHOLD);
  1515. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1516. if (spr_is_abort(s->spr)) {
  1517. ssh_spr_close(s->ppl.ssh, s->spr, "kex warning");
  1518. return;
  1519. }
  1520. }
  1521. if (s->warn_hk) {
  1522. int j, k;
  1523. const char **betteralgs = NULL;
  1524. size_t nbetter = 0, bettersize = 0;
  1525. /*
  1526. * Change warning box wording depending on why we chose a
  1527. * warning-level host key algorithm. If it's because
  1528. * that's all we have *cached*, list the host keys we
  1529. * could usefully cross-certify. Otherwise, use the same
  1530. * standard wording as any other weak crypto primitive.
  1531. */
  1532. for (j = 0; j < s->n_uncert_hostkeys; j++) {
  1533. const struct ssh_signkey_with_user_pref_id *hktype =
  1534. &ssh2_hostkey_algs[s->uncert_hostkeys[j]];
  1535. bool better = false;
  1536. for (k = 0; k < HK_MAX; k++) {
  1537. int id = conf_get_int_int(s->conf, CONF_ssh_hklist, k);
  1538. if (id == HK_WARN) {
  1539. break;
  1540. } else if (id == hktype->id) {
  1541. better = true;
  1542. break;
  1543. }
  1544. }
  1545. if (better) {
  1546. sgrowarray(betteralgs, bettersize, nbetter);
  1547. betteralgs[nbetter++] = hktype->alg->ssh_id;
  1548. }
  1549. }
  1550. if (betteralgs) {
  1551. /* Use the special warning prompt that lets us provide
  1552. * a list of better algorithms */
  1553. sgrowarray(betteralgs, bettersize, nbetter);
  1554. betteralgs[nbetter] = NULL;
  1555. s->spr = confirm_weak_cached_hostkey(
  1556. ppl_get_iseat(&s->ppl), s->hostkey_alg->ssh_id, betteralgs,
  1557. ssh2_transport_dialog_callback, s);
  1558. sfree(betteralgs);
  1559. } else {
  1560. /* If none exist, use the more general 'weak crypto'
  1561. * warning prompt */
  1562. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1563. s, "host key type", s->hostkey_alg->ssh_id,
  1564. s->hostkey_alg, WCR_BELOW_THRESHOLD);
  1565. }
  1566. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1567. if (spr_is_abort(s->spr)) {
  1568. ssh_spr_close(s->ppl.ssh, s->spr, "host key warning");
  1569. return;
  1570. }
  1571. }
  1572. if (s->warn_cscipher) {
  1573. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1574. s, "client-to-server cipher", s->out.cipher->ssh2_id,
  1575. s->out.cipher, WCR_BELOW_THRESHOLD);
  1576. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1577. if (spr_is_abort(s->spr)) {
  1578. ssh_spr_close(s->ppl.ssh, s->spr, "cipher warning");
  1579. return;
  1580. }
  1581. }
  1582. if (s->warn_sccipher) {
  1583. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1584. s, "server-to-client cipher", s->in.cipher->ssh2_id,
  1585. s->in.cipher, WCR_BELOW_THRESHOLD);
  1586. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1587. if (spr_is_abort(s->spr)) {
  1588. ssh_spr_close(s->ppl.ssh, s->spr, "cipher warning");
  1589. return;
  1590. }
  1591. }
  1592. {
  1593. s->terrapin.csvuln = terrapin_vulnerable(s->strict_kex, s->cstrans);
  1594. s->terrapin.scvuln = terrapin_vulnerable(s->strict_kex, s->sctrans);
  1595. s->terrapin.wcr = WCR_TERRAPIN;
  1596. if (s->terrapin.csvuln || s->terrapin.scvuln) {
  1597. ppl_logevent("SSH connection is vulnerable to 'Terrapin' attack "
  1598. "(CVE-2023-48795)");
  1599. if (try_to_avoid_terrapin(s))
  1600. s->terrapin.wcr = WCR_TERRAPIN_AVOIDABLE;
  1601. }
  1602. if (s->terrapin.csvuln) {
  1603. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1604. s, "client-to-server cipher", s->terrapin.csvuln,
  1605. terrapin_weakness, s->terrapin.wcr);
  1606. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1607. if (spr_is_abort(s->spr)) {
  1608. ssh_spr_close(s->ppl.ssh, s->spr, "vulnerability warning");
  1609. return;
  1610. }
  1611. }
  1612. if (s->terrapin.scvuln) {
  1613. s->spr = ssh2_transport_confirm_weak_crypto_primitive(
  1614. s, "server-to-client cipher", s->terrapin.scvuln,
  1615. terrapin_weakness, s->terrapin.wcr);
  1616. crMaybeWaitUntilV(s->spr.kind != SPRK_INCOMPLETE);
  1617. if (spr_is_abort(s->spr)) {
  1618. ssh_spr_close(s->ppl.ssh, s->spr, "vulnerability warning");
  1619. return;
  1620. }
  1621. }
  1622. if (s->terrapin.csvuln || s->terrapin.scvuln) {
  1623. ppl_logevent("Continuing despite 'Terrapin' vulnerability, "
  1624. "at user request");
  1625. }
  1626. }
  1627. /*
  1628. * If the other side has sent an initial key exchange packet that
  1629. * we must treat as a wrong guess, wait for it, and discard it.
  1630. */
  1631. if (s->ignorepkt)
  1632. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1633. /*
  1634. * Actually perform the key exchange.
  1635. */
  1636. s->exhash = ssh_hash_new(s->kex_alg->hash);
  1637. if (s->kex_shared_secret)
  1638. strbuf_free(s->kex_shared_secret);
  1639. s->kex_shared_secret = strbuf_new_nm();
  1640. put_stringz(s->exhash, s->client_greeting);
  1641. put_stringz(s->exhash, s->server_greeting);
  1642. put_string(s->exhash, s->client_kexinit->u, s->client_kexinit->len);
  1643. put_string(s->exhash, s->server_kexinit->u, s->server_kexinit->len);
  1644. s->crStateKex = 0;
  1645. while (1) {
  1646. bool aborted = false;
  1647. ssh2kex_coroutine(s, &aborted);
  1648. if (aborted)
  1649. return; /* disaster: our entire state has been freed */
  1650. if (!s->crStateKex)
  1651. break; /* kex phase has terminated normally */
  1652. crReturnV;
  1653. }
  1654. /*
  1655. * The exchange hash from the very first key exchange is also
  1656. * the session id, used in session key construction and
  1657. * authentication.
  1658. */
  1659. if (!s->got_session_id) {
  1660. assert(sizeof(s->exchange_hash) <= sizeof(s->session_id));
  1661. memcpy(s->session_id, s->exchange_hash, sizeof(s->exchange_hash));
  1662. s->session_id_len = s->kex_alg->hash->hlen;
  1663. assert(s->session_id_len <= sizeof(s->session_id));
  1664. s->got_session_id = true;
  1665. }
  1666. /*
  1667. * Send SSH2_MSG_NEWKEYS.
  1668. */
  1669. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_NEWKEYS);
  1670. pq_push(s->ppl.out_pq, pktout);
  1671. /* Start counting down the outgoing-data limit for these cipher keys. */
  1672. dts_reset(&s->stats->out, s->max_data_size);
  1673. /*
  1674. * Force the BPP to synchronously marshal all packets up to and
  1675. * including that NEWKEYS into wire format, before we switch over
  1676. * to new crypto.
  1677. */
  1678. ssh_bpp_handle_output(s->ppl.bpp);
  1679. /*
  1680. * We've sent outgoing NEWKEYS, so create and initialise outgoing
  1681. * session keys.
  1682. */
  1683. {
  1684. strbuf *cipher_key = strbuf_new_nm();
  1685. strbuf *cipher_iv = strbuf_new_nm();
  1686. strbuf *mac_key = strbuf_new_nm();
  1687. if (s->out.cipher) {
  1688. ssh2_mkkey(s, cipher_iv, s->kex_shared_secret, s->exchange_hash,
  1689. 'A' + s->out.mkkey_adjust, s->out.cipher->blksize);
  1690. ssh2_mkkey(s, cipher_key, s->kex_shared_secret, s->exchange_hash,
  1691. 'C' + s->out.mkkey_adjust,
  1692. s->out.cipher->padded_keybytes);
  1693. }
  1694. if (s->out.mac) {
  1695. ssh2_mkkey(s, mac_key, s->kex_shared_secret, s->exchange_hash,
  1696. 'E' + s->out.mkkey_adjust, s->out.mac->keylen);
  1697. }
  1698. ssh2_bpp_new_outgoing_crypto(
  1699. s->ppl.bpp,
  1700. s->out.cipher, cipher_key->u, cipher_iv->u,
  1701. s->out.mac, s->out.etm_mode, mac_key->u,
  1702. s->out.comp, s->out.comp_delayed,
  1703. s->strict_kex);
  1704. s->enabled_outgoing_crypto = true;
  1705. strbuf_free(cipher_key);
  1706. strbuf_free(cipher_iv);
  1707. strbuf_free(mac_key);
  1708. }
  1709. /*
  1710. * If that was our first key exchange, this is the moment to send
  1711. * our EXT_INFO, if we're sending one.
  1712. */
  1713. if (!s->post_newkeys_ext_info) {
  1714. s->post_newkeys_ext_info = true; /* never do this again */
  1715. if (s->can_send_ext_info) {
  1716. strbuf *extinfo = strbuf_new();
  1717. uint32_t n_exts = 0;
  1718. if (s->ssc) {
  1719. /* Server->client EXT_INFO lists our supported user
  1720. * key algorithms. */
  1721. n_exts++;
  1722. put_stringz(extinfo, "server-sig-algs");
  1723. { // WINSCP
  1724. strbuf *list = strbuf_new();
  1725. size_t i; // WINSCP
  1726. for (i = 0; i < n_keyalgs; i++)
  1727. add_to_commasep(list, all_keyalgs[i]->ssh_id);
  1728. put_stringsb(extinfo, list);
  1729. } // WINSCP
  1730. } else {
  1731. /* Client->server EXT_INFO is currently not sent, but here's
  1732. * where we should put things in it if we ever want to. */
  1733. }
  1734. /* Only send EXT_INFO if it's non-empty */
  1735. if (n_exts) {
  1736. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_EXT_INFO);
  1737. put_uint32(pktout, n_exts);
  1738. put_datapl(pktout, ptrlen_from_strbuf(extinfo));
  1739. pq_push(s->ppl.out_pq, pktout);
  1740. }
  1741. strbuf_free(extinfo);
  1742. }
  1743. }
  1744. /*
  1745. * Now our end of the key exchange is complete, we can send all
  1746. * our queued higher-layer packets. Transfer the whole of the next
  1747. * layer's outgoing queue on to our own.
  1748. */
  1749. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  1750. ssh_sendbuffer_changed(s->ppl.ssh);
  1751. /*
  1752. * Expect SSH2_MSG_NEWKEYS from server.
  1753. */
  1754. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1755. if (pktin->type != SSH2_MSG_NEWKEYS) {
  1756. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1757. "expecting SSH_MSG_NEWKEYS, type %d (%s)",
  1758. pktin->type,
  1759. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1760. s->ppl.bpp->pls->actx,
  1761. pktin->type));
  1762. return;
  1763. }
  1764. /* Start counting down the incoming-data limit for these cipher keys. */
  1765. dts_reset(&s->stats->in, s->max_data_size);
  1766. /*
  1767. * We've seen incoming NEWKEYS, so create and initialise
  1768. * incoming session keys.
  1769. */
  1770. {
  1771. strbuf *cipher_key = strbuf_new_nm();
  1772. strbuf *cipher_iv = strbuf_new_nm();
  1773. strbuf *mac_key = strbuf_new_nm();
  1774. if (s->in.cipher) {
  1775. ssh2_mkkey(s, cipher_iv, s->kex_shared_secret, s->exchange_hash,
  1776. 'A' + s->in.mkkey_adjust, s->in.cipher->blksize);
  1777. ssh2_mkkey(s, cipher_key, s->kex_shared_secret, s->exchange_hash,
  1778. 'C' + s->in.mkkey_adjust,
  1779. s->in.cipher->padded_keybytes);
  1780. }
  1781. if (s->in.mac) {
  1782. ssh2_mkkey(s, mac_key, s->kex_shared_secret, s->exchange_hash,
  1783. 'E' + s->in.mkkey_adjust, s->in.mac->keylen);
  1784. }
  1785. ssh2_bpp_new_incoming_crypto(
  1786. s->ppl.bpp,
  1787. s->in.cipher, cipher_key->u, cipher_iv->u,
  1788. s->in.mac, s->in.etm_mode, mac_key->u,
  1789. s->in.comp, s->in.comp_delayed,
  1790. s->strict_kex);
  1791. s->enabled_incoming_crypto = true;
  1792. strbuf_free(cipher_key);
  1793. strbuf_free(cipher_iv);
  1794. strbuf_free(mac_key);
  1795. }
  1796. /*
  1797. * Free shared secret.
  1798. */
  1799. strbuf_free(s->kex_shared_secret);
  1800. s->kex_shared_secret = NULL;
  1801. /*
  1802. * Update the specials menu to list the remaining uncertified host
  1803. * keys.
  1804. */
  1805. seat_update_specials_menu(s->ppl.seat);
  1806. /*
  1807. * Key exchange is over. Loop straight back round if we have a
  1808. * deferred rekey reason.
  1809. */
  1810. if (s->deferred_rekey_reason) {
  1811. ppl_logevent("%s", s->deferred_rekey_reason);
  1812. pktin = NULL;
  1813. s->deferred_rekey_reason = NULL;
  1814. goto begin_key_exchange;
  1815. }
  1816. /*
  1817. * Otherwise, schedule a timer for our next rekey.
  1818. */
  1819. s->kex_in_progress = false;
  1820. s->last_rekey = GETTICKCOUNT();
  1821. (void) ssh2_transport_timer_update(s, 0);
  1822. /*
  1823. * Now we're encrypting. Get the next-layer protocol started if it
  1824. * hasn't already, and then sit here waiting for reasons to go
  1825. * back to the start and do a repeat key exchange. One of those
  1826. * reasons is that we receive KEXINIT from the other end; the
  1827. * other is if we find rekey_reason is non-NULL, i.e. we've
  1828. * decided to initiate a rekey ourselves for some reason.
  1829. */
  1830. if (!s->higher_layer_ok) {
  1831. if (!s->hostkeys) {
  1832. /* We're the client, so send SERVICE_REQUEST. */
  1833. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_SERVICE_REQUEST);
  1834. put_stringz(pktout, s->higher_layer->vt->name);
  1835. pq_push(s->ppl.out_pq, pktout);
  1836. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1837. if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
  1838. ssh_sw_abort(s->ppl.ssh, "Server refused request to start "
  1839. "'%s' protocol", s->higher_layer->vt->name);
  1840. return;
  1841. }
  1842. } else {
  1843. ptrlen service_name;
  1844. /* We're the server, so expect SERVICE_REQUEST. */
  1845. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1846. if (pktin->type != SSH2_MSG_SERVICE_REQUEST) {
  1847. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1848. "expecting SERVICE_REQUEST, type %d (%s)",
  1849. pktin->type,
  1850. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1851. s->ppl.bpp->pls->actx,
  1852. pktin->type));
  1853. return;
  1854. }
  1855. service_name = get_string(pktin);
  1856. if (!ptrlen_eq_string(service_name, s->higher_layer->vt->name)) {
  1857. ssh_proto_error(s->ppl.ssh, "Client requested service "
  1858. "'%.*s' when we only support '%s'",
  1859. PTRLEN_PRINTF(service_name),
  1860. s->higher_layer->vt->name);
  1861. return;
  1862. }
  1863. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_SERVICE_ACCEPT);
  1864. put_stringz(pktout, s->higher_layer->vt->name);
  1865. pq_push(s->ppl.out_pq, pktout);
  1866. }
  1867. s->higher_layer_ok = true;
  1868. queue_idempotent_callback(&s->higher_layer->ic_process_queue);
  1869. }
  1870. s->rekey_class = RK_NONE;
  1871. do {
  1872. crReturnV;
  1873. /* Pass through outgoing packets from the higher layer. */
  1874. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  1875. ssh_sendbuffer_changed(s->ppl.ssh);
  1876. /* Wait for either a KEXINIT, or something setting
  1877. * s->rekey_class. This call to ssh2_transport_pop also has
  1878. * the side effect of transferring incoming packets _to_ the
  1879. * higher layer (via filter_queue). */
  1880. if ((pktin = ssh2_transport_pop(s)) != NULL) {
  1881. if (pktin->type != SSH2_MSG_KEXINIT) {
  1882. ssh_proto_error(s->ppl.ssh, "Received unexpected transport-"
  1883. "layer packet outside a key exchange, "
  1884. "type %d (%s)", pktin->type,
  1885. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1886. s->ppl.bpp->pls->actx,
  1887. pktin->type));
  1888. return;
  1889. }
  1890. pq_push_front(s->ppl.in_pq, pktin);
  1891. ppl_logevent("Remote side initiated key re-exchange");
  1892. s->rekey_class = RK_SERVER;
  1893. }
  1894. if (s->rekey_class == RK_POST_USERAUTH) {
  1895. /*
  1896. * userauth has seen a USERAUTH_SUCCESS. This may be the
  1897. * moment to do an immediate rekey with different
  1898. * parameters. But it may not; so here we turn that rekey
  1899. * class into either RK_NONE or RK_NORMAL.
  1900. *
  1901. * Currently the only reason for this is if we've done a
  1902. * GSS key exchange and don't have anything in our
  1903. * transient hostkey cache, in which case we should make
  1904. * an attempt to populate the cache now.
  1905. */
  1906. if (s->need_gss_transient_hostkey) {
  1907. s->rekey_reason = "populating transient host key cache";
  1908. s->rekey_class = RK_NORMAL;
  1909. } else {
  1910. /* No need to rekey at this time. */
  1911. s->rekey_class = RK_NONE;
  1912. }
  1913. }
  1914. if (!s->rekey_class) {
  1915. /* If we don't yet have any other reason to rekey, check
  1916. * if we've hit our data limit in either direction. */
  1917. if (s->stats->in.expired) {
  1918. s->rekey_reason = "too much data received";
  1919. s->rekey_class = RK_NORMAL;
  1920. } else if (s->stats->out.expired) {
  1921. s->rekey_reason = "too much data sent";
  1922. s->rekey_class = RK_NORMAL;
  1923. }
  1924. }
  1925. if (s->rekey_class != RK_NONE && s->rekey_class != RK_SERVER) {
  1926. /*
  1927. * Special case: if the server bug is set that doesn't
  1928. * allow rekeying, we give a different log message and
  1929. * continue waiting. (If such a server _initiates_ a
  1930. * rekey, we process it anyway!)
  1931. */
  1932. if ((s->ppl.remote_bugs & BUG_SSH2_REKEY)) {
  1933. ppl_logevent("Remote bug prevents key re-exchange (%s)",
  1934. s->rekey_reason);
  1935. /* Reset the counters, so that at least this message doesn't
  1936. * hit the event log _too_ often. */
  1937. dts_reset(&s->stats->in, s->max_data_size);
  1938. dts_reset(&s->stats->out, s->max_data_size);
  1939. (void) ssh2_transport_timer_update(s, 0);
  1940. s->rekey_class = RK_NONE;
  1941. } else {
  1942. ppl_logevent("Initiating key re-exchange (%s)",
  1943. s->rekey_reason);
  1944. }
  1945. }
  1946. } while (s->rekey_class == RK_NONE);
  1947. /* Once we exit the above loop, we really are rekeying. */
  1948. goto begin_key_exchange;
  1949. crFinishV;
  1950. }
  1951. static void ssh2_transport_higher_layer_packet_callback(void *context)
  1952. {
  1953. PacketProtocolLayer *ppl = (PacketProtocolLayer *)context;
  1954. ssh_ppl_process_queue(ppl);
  1955. }
  1956. static void ssh2_transport_timer(void *ctx, unsigned long now)
  1957. {
  1958. struct ssh2_transport_state *s = (struct ssh2_transport_state *)ctx;
  1959. unsigned long mins;
  1960. unsigned long ticks;
  1961. // WINSCP: our WINSCP_QUERY_TIMER implementation of schedule_timer
  1962. // does not guarantee the `now` to be exactly as scheduled
  1963. if (s->kex_in_progress || now < s->next_rekey)
  1964. return;
  1965. mins = sanitise_rekey_time(conf_get_int(s->conf, CONF_ssh_rekey_time), 60);
  1966. if (mins == 0)
  1967. return;
  1968. /* Rekey if enough time has elapsed */
  1969. ticks = mins * 60 * TICKSPERSEC;
  1970. if (now - s->last_rekey > ticks - 30*TICKSPERSEC) {
  1971. s->rekey_reason = "timeout";
  1972. s->rekey_class = RK_NORMAL;
  1973. queue_idempotent_callback(&s->ppl.ic_process_queue);
  1974. return;
  1975. }
  1976. #ifndef NO_GSSAPI
  1977. /*
  1978. * Rekey now if we have a new cred or context expires this cycle,
  1979. * but not if this is unsafe.
  1980. */
  1981. if (conf_get_int(s->conf, CONF_gssapirekey)) {
  1982. ssh2_transport_gss_update(s, false);
  1983. if ((s->gss_status & GSS_KEX_CAPABLE) != 0 &&
  1984. (s->gss_status & GSS_CTXT_MAYFAIL) == 0 &&
  1985. (s->gss_status & (GSS_CRED_UPDATED|GSS_CTXT_EXPIRES)) != 0) {
  1986. s->rekey_reason = "GSS credentials updated";
  1987. s->rekey_class = RK_GSS_UPDATE;
  1988. queue_idempotent_callback(&s->ppl.ic_process_queue);
  1989. return;
  1990. }
  1991. }
  1992. #endif
  1993. /* Try again later. */
  1994. (void) ssh2_transport_timer_update(s, 0);
  1995. }
  1996. /*
  1997. * The rekey_time is zero except when re-configuring.
  1998. *
  1999. * We either schedule the next timer and return false, or return true
  2000. * to run the callback now, which will call us again to re-schedule on
  2001. * completion.
  2002. */
  2003. static bool ssh2_transport_timer_update(struct ssh2_transport_state *s,
  2004. unsigned long rekey_time)
  2005. {
  2006. unsigned long mins;
  2007. unsigned long ticks;
  2008. mins = sanitise_rekey_time(conf_get_int(s->conf, CONF_ssh_rekey_time), 60);
  2009. ticks = mins * 60 * TICKSPERSEC;
  2010. /* Handle change from previous setting */
  2011. if (rekey_time != 0 && rekey_time != mins) {
  2012. unsigned long next;
  2013. unsigned long now = GETTICKCOUNT();
  2014. mins = rekey_time;
  2015. ticks = mins * 60 * TICKSPERSEC;
  2016. next = s->last_rekey + ticks;
  2017. /* If overdue, caller will rekey synchronously now */
  2018. if (now - s->last_rekey > ticks)
  2019. return true;
  2020. ticks = next - now;
  2021. }
  2022. #ifndef NO_GSSAPI
  2023. if (s->gss_kex_used) {
  2024. /*
  2025. * If we've used GSSAPI key exchange, then we should
  2026. * periodically check whether we need to do another one to
  2027. * pass new credentials to the server.
  2028. */
  2029. unsigned long gssmins;
  2030. /* Check cascade conditions more frequently if configured */
  2031. gssmins = sanitise_rekey_time(
  2032. conf_get_int(s->conf, CONF_gssapirekey), GSS_DEF_REKEY_MINS);
  2033. if (gssmins > 0) {
  2034. if (gssmins < mins)
  2035. ticks = (mins = gssmins) * 60 * TICKSPERSEC;
  2036. if ((s->gss_status & GSS_KEX_CAPABLE) != 0) {
  2037. /*
  2038. * Run next timer even sooner if it would otherwise be
  2039. * too close to the context expiration time
  2040. */
  2041. if ((s->gss_status & GSS_CTXT_EXPIRES) == 0 &&
  2042. s->gss_ctxt_lifetime - mins * 60 < 2 * MIN_CTXT_LIFETIME)
  2043. ticks -= 2 * MIN_CTXT_LIFETIME * TICKSPERSEC;
  2044. }
  2045. }
  2046. }
  2047. #endif
  2048. /* Schedule the next timer */
  2049. s->next_rekey = schedule_timer(ticks, ssh2_transport_timer, s);
  2050. return false;
  2051. }
  2052. void ssh2_transport_dialog_callback(void *vctx, SeatPromptResult spr)
  2053. {
  2054. struct ssh2_transport_state *s = (struct ssh2_transport_state *)vctx;
  2055. s->spr = spr;
  2056. ssh_ppl_process_queue(&s->ppl);
  2057. }
  2058. #ifndef NO_GSSAPI
  2059. /*
  2060. * This is called at the beginning of each SSH rekey to determine
  2061. * whether we are GSS capable, and if we did GSS key exchange, and are
  2062. * delegating credentials, it is also called periodically to determine
  2063. * whether we should rekey in order to delegate (more) fresh
  2064. * credentials. This is called "credential cascading".
  2065. *
  2066. * On Windows, with SSPI, we may not get the credential expiration, as
  2067. * Windows automatically renews from cached passwords, so the
  2068. * credential effectively never expires. Since we still want to
  2069. * cascade when the local TGT is updated, we use the expiration of a
  2070. * newly obtained context as a proxy for the expiration of the TGT.
  2071. */
  2072. static void ssh2_transport_gss_update(struct ssh2_transport_state *s,
  2073. bool definitely_rekeying)
  2074. {
  2075. PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
  2076. int gss_stat;
  2077. time_t gss_cred_expiry;
  2078. unsigned long mins;
  2079. Ssh_gss_buf gss_sndtok;
  2080. Ssh_gss_buf gss_rcvtok;
  2081. Ssh_gss_ctx gss_ctx;
  2082. s->gss_status = 0;
  2083. /*
  2084. * Nothing to do if no GSSAPI libraries are configured or GSSAPI
  2085. * auth is not enabled.
  2086. */
  2087. if (s->shgss->libs->nlibraries == 0)
  2088. return;
  2089. if (!conf_get_bool(s->conf, CONF_try_gssapi_auth) &&
  2090. !conf_get_bool(s->conf, CONF_try_gssapi_kex))
  2091. return;
  2092. /* Import server name and cache it */
  2093. if (s->shgss->srv_name == GSS_C_NO_NAME) {
  2094. gss_stat = s->shgss->lib->import_name(
  2095. s->shgss->lib, s->fullhostname, &s->shgss->srv_name);
  2096. if (gss_stat != SSH_GSS_OK) {
  2097. if (gss_stat == SSH_GSS_BAD_HOST_NAME)
  2098. ppl_logevent("GSSAPI import name failed - Bad service name;"
  2099. " won't use GSS key exchange");
  2100. else
  2101. ppl_logevent("GSSAPI import name failed;"
  2102. " won't use GSS key exchange");
  2103. return;
  2104. }
  2105. }
  2106. /*
  2107. * Do we (still) have credentials? Capture the credential
  2108. * expiration when available
  2109. */
  2110. gss_stat = s->shgss->lib->acquire_cred(
  2111. s->shgss->lib, &gss_ctx, &gss_cred_expiry);
  2112. if (gss_stat != SSH_GSS_OK)
  2113. return;
  2114. SSH_GSS_CLEAR_BUF(&gss_sndtok);
  2115. SSH_GSS_CLEAR_BUF(&gss_rcvtok);
  2116. /*
  2117. * When acquire_cred yields no useful expiration, get a proxy for
  2118. * the cred expiration from the context expiration.
  2119. */
  2120. gss_stat = s->shgss->lib->init_sec_context(
  2121. s->shgss->lib, &gss_ctx, s->shgss->srv_name,
  2122. 0 /* don't delegate */, &gss_rcvtok, &gss_sndtok,
  2123. (gss_cred_expiry == GSS_NO_EXPIRATION ? &gss_cred_expiry : NULL),
  2124. &s->gss_ctxt_lifetime);
  2125. /* This context was for testing only. */
  2126. if (gss_ctx)
  2127. s->shgss->lib->release_cred(s->shgss->lib, &gss_ctx);
  2128. if (gss_stat != SSH_GSS_OK &&
  2129. gss_stat != SSH_GSS_S_CONTINUE_NEEDED) {
  2130. /*
  2131. * No point in verbosely interrupting the user to tell them we
  2132. * couldn't get GSS credentials, if this was only a check
  2133. * between key exchanges to see if fresh ones were available.
  2134. * When we do do a rekey, this message (if displayed) will
  2135. * appear among the standard rekey blurb, but when we're not,
  2136. * it shouldn't pop up all the time regardless.
  2137. */
  2138. if (definitely_rekeying)
  2139. ppl_logevent("No GSSAPI security context available");
  2140. return;
  2141. }
  2142. if (gss_sndtok.length)
  2143. s->shgss->lib->free_tok(s->shgss->lib, &gss_sndtok);
  2144. s->gss_status |= GSS_KEX_CAPABLE;
  2145. /*
  2146. * When rekeying to cascade, avoid doing this too close to the
  2147. * context expiration time, since the key exchange might fail.
  2148. */
  2149. if (s->gss_ctxt_lifetime < MIN_CTXT_LIFETIME)
  2150. s->gss_status |= GSS_CTXT_MAYFAIL;
  2151. /*
  2152. * If we're not delegating credentials, rekeying is not used to
  2153. * refresh them. We must avoid setting GSS_CRED_UPDATED or
  2154. * GSS_CTXT_EXPIRES when credential delegation is disabled.
  2155. */
  2156. if (!conf_get_bool(s->conf, CONF_gssapifwd))
  2157. return;
  2158. if (s->gss_cred_expiry != GSS_NO_EXPIRATION &&
  2159. difftime(gss_cred_expiry, s->gss_cred_expiry) > 0)
  2160. s->gss_status |= GSS_CRED_UPDATED;
  2161. mins = sanitise_rekey_time(
  2162. conf_get_int(s->conf, CONF_gssapirekey), GSS_DEF_REKEY_MINS);
  2163. if (mins > 0 && s->gss_ctxt_lifetime <= mins * 60)
  2164. s->gss_status |= GSS_CTXT_EXPIRES;
  2165. }
  2166. #endif /* NO_GSSAPI */
  2167. ptrlen ssh2_transport_get_session_id(PacketProtocolLayer *ppl)
  2168. {
  2169. struct ssh2_transport_state *s;
  2170. assert(ppl->vt == &ssh2_transport_vtable);
  2171. s = container_of(ppl, struct ssh2_transport_state, ppl);
  2172. assert(s->got_session_id);
  2173. return make_ptrlen(s->session_id, s->session_id_len);
  2174. }
  2175. void ssh2_transport_notify_auth_done(PacketProtocolLayer *ppl)
  2176. {
  2177. struct ssh2_transport_state *s;
  2178. assert(ppl->vt == &ssh2_transport_vtable);
  2179. s = container_of(ppl, struct ssh2_transport_state, ppl);
  2180. s->rekey_reason = NULL; /* will be filled in later */
  2181. s->rekey_class = RK_POST_USERAUTH;
  2182. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2183. }
  2184. static bool ssh2_transport_get_specials(
  2185. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
  2186. {
  2187. struct ssh2_transport_state *s =
  2188. container_of(ppl, struct ssh2_transport_state, ppl);
  2189. bool need_separator = false;
  2190. bool toret = false;
  2191. if (ssh_ppl_get_specials(s->higher_layer, add_special, ctx)) {
  2192. need_separator = true;
  2193. toret = true;
  2194. }
  2195. /*
  2196. * Don't bother offering rekey-based specials if we've decided the
  2197. * remote won't cope with it, since we wouldn't bother sending it
  2198. * if asked anyway.
  2199. */
  2200. if (!(s->ppl.remote_bugs & BUG_SSH2_REKEY)) {
  2201. if (need_separator) {
  2202. add_special(ctx, NULL, SS_SEP, 0);
  2203. need_separator = false;
  2204. }
  2205. add_special(ctx, "Repeat key exchange", SS_REKEY, 0);
  2206. toret = true;
  2207. if (s->n_uncert_hostkeys) {
  2208. int i;
  2209. add_special(ctx, NULL, SS_SEP, 0);
  2210. add_special(ctx, "Cache new host key type", SS_SUBMENU, 0);
  2211. for (i = 0; i < s->n_uncert_hostkeys; i++) {
  2212. const ssh_keyalg *alg =
  2213. ssh2_hostkey_algs[s->uncert_hostkeys[i]].alg;
  2214. add_special(ctx, alg->ssh_id, SS_XCERT, s->uncert_hostkeys[i]);
  2215. }
  2216. add_special(ctx, NULL, SS_EXITMENU, 0);
  2217. }
  2218. }
  2219. return toret;
  2220. }
  2221. static void ssh2_transport_special_cmd(PacketProtocolLayer *ppl,
  2222. SessionSpecialCode code, int arg)
  2223. {
  2224. struct ssh2_transport_state *s =
  2225. container_of(ppl, struct ssh2_transport_state, ppl);
  2226. if (code == SS_REKEY) {
  2227. if (!s->kex_in_progress) {
  2228. s->rekey_reason = "at user request";
  2229. s->rekey_class = RK_NORMAL;
  2230. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2231. }
  2232. } else if (code == SS_XCERT) {
  2233. if (!s->kex_in_progress) {
  2234. s->cross_certifying = s->hostkey_alg = ssh2_hostkey_algs[arg].alg;
  2235. s->rekey_reason = "cross-certifying new host key";
  2236. s->rekey_class = RK_NORMAL;
  2237. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2238. }
  2239. } else {
  2240. /* Send everything else to the next layer up. This includes
  2241. * SS_PING/SS_NOP, which we _could_ handle here - but it's
  2242. * better to put them in the connection layer, so they'll
  2243. * still work in bare connection mode. */
  2244. ssh_ppl_special_cmd(s->higher_layer, code, arg);
  2245. }
  2246. }
  2247. /* Safely convert rekey_time to unsigned long minutes */
  2248. static unsigned long sanitise_rekey_time(int rekey_time, unsigned long def)
  2249. {
  2250. if (rekey_time < 0 || rekey_time > MAX_TICK_MINS)
  2251. rekey_time = def;
  2252. return (unsigned long)rekey_time;
  2253. }
  2254. static void ssh2_transport_set_max_data_size(struct ssh2_transport_state *s)
  2255. {
  2256. s->max_data_size = parse_blocksize(
  2257. conf_get_str(s->conf, CONF_ssh_rekey_data));
  2258. }
  2259. static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf)
  2260. {
  2261. struct ssh2_transport_state *s;
  2262. const char *rekey_reason = NULL;
  2263. bool rekey_mandatory = false;
  2264. unsigned long old_max_data_size, rekey_time;
  2265. int i;
  2266. assert(ppl->vt == &ssh2_transport_vtable);
  2267. s = container_of(ppl, struct ssh2_transport_state, ppl);
  2268. rekey_time = sanitise_rekey_time(
  2269. conf_get_int(conf, CONF_ssh_rekey_time), 60);
  2270. if (ssh2_transport_timer_update(s, rekey_time))
  2271. rekey_reason = "timeout shortened";
  2272. old_max_data_size = s->max_data_size;
  2273. ssh2_transport_set_max_data_size(s);
  2274. if (old_max_data_size != s->max_data_size &&
  2275. s->max_data_size != 0) {
  2276. if (s->max_data_size < old_max_data_size) {
  2277. unsigned long diff = old_max_data_size - s->max_data_size;
  2278. dts_consume(&s->stats->out, diff);
  2279. dts_consume(&s->stats->in, diff);
  2280. if (s->stats->out.expired || s->stats->in.expired)
  2281. rekey_reason = "data limit lowered";
  2282. } else {
  2283. unsigned long diff = s->max_data_size - old_max_data_size;
  2284. if (s->stats->out.running)
  2285. s->stats->out.remaining += diff;
  2286. if (s->stats->in.running)
  2287. s->stats->in.remaining += diff;
  2288. }
  2289. }
  2290. if (conf_get_bool(s->conf, CONF_compression) !=
  2291. conf_get_bool(conf, CONF_compression)) {
  2292. rekey_reason = "compression setting changed";
  2293. rekey_mandatory = true;
  2294. }
  2295. for (i = 0; i < CIPHER_MAX; i++)
  2296. if (conf_get_int_int(s->conf, CONF_ssh_cipherlist, i) !=
  2297. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  2298. rekey_reason = "cipher settings changed";
  2299. rekey_mandatory = true;
  2300. }
  2301. if (conf_get_bool(s->conf, CONF_ssh2_des_cbc) !=
  2302. conf_get_bool(conf, CONF_ssh2_des_cbc)) {
  2303. rekey_reason = "cipher settings changed";
  2304. rekey_mandatory = true;
  2305. }
  2306. conf_free(s->conf);
  2307. s->conf = conf_copy(conf);
  2308. if (rekey_reason) {
  2309. if (!s->kex_in_progress && !ssh2_bpp_rekey_inadvisable(s->ppl.bpp)) {
  2310. s->rekey_reason = rekey_reason;
  2311. s->rekey_class = RK_NORMAL;
  2312. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2313. } else if (rekey_mandatory) {
  2314. s->deferred_rekey_reason = rekey_reason;
  2315. }
  2316. }
  2317. /* Also pass the configuration along to our higher layer */
  2318. ssh_ppl_reconfigure(s->higher_layer, conf);
  2319. }
  2320. static int weak_algorithm_compare(void *av, void *bv)
  2321. {
  2322. uintptr_t a = (uintptr_t)av, b = (uintptr_t)bv;
  2323. return a < b ? -1 : a > b ? +1 : 0;
  2324. }
  2325. static int ca_blob_compare(void *av, void *bv)
  2326. {
  2327. host_ca *a = (host_ca *)av, *b = (host_ca *)bv;
  2328. strbuf *apk = a->ca_public_key, *bpk = b->ca_public_key;
  2329. /* Ordering by public key is arbitrary here, so do whatever is easiest */
  2330. if (apk->len < bpk->len)
  2331. return -1;
  2332. if (apk->len > bpk->len)
  2333. return +1;
  2334. return memcmp(apk->u, bpk->u, apk->len);
  2335. }
  2336. /*
  2337. * Wrapper on confirm_weak_crypto_primitive(), which uses the
  2338. * tree234 s->weak_algorithms_consented_to to ensure we ask at most
  2339. * once about any given crypto primitive.
  2340. */
  2341. static SeatPromptResult ssh2_transport_confirm_weak_crypto_primitive(
  2342. struct ssh2_transport_state *s, const char *type, const char *name,
  2343. const void *alg, WeakCryptoReason wcr)
  2344. {
  2345. if (find234(s->weak_algorithms_consented_to, (void *)alg, NULL))
  2346. return SPR_OK;
  2347. add234(s->weak_algorithms_consented_to, (void *)alg);
  2348. return confirm_weak_crypto_primitive(
  2349. ppl_get_iseat(&s->ppl), type, name, ssh2_transport_dialog_callback,
  2350. s, wcr);
  2351. }
  2352. static size_t ssh2_transport_queued_data_size(PacketProtocolLayer *ppl)
  2353. {
  2354. struct ssh2_transport_state *s =
  2355. container_of(ppl, struct ssh2_transport_state, ppl);
  2356. return (ssh_ppl_default_queued_data_size(ppl) +
  2357. ssh_ppl_queued_data_size(s->higher_layer));
  2358. }
  2359. static void ssh2_transport_final_output(PacketProtocolLayer *ppl)
  2360. {
  2361. struct ssh2_transport_state *s =
  2362. container_of(ppl, struct ssh2_transport_state, ppl);
  2363. ssh_ppl_final_output(s->higher_layer);
  2364. }
  2365. /* Check the settings for a transport direction to see if they're
  2366. * vulnerable to the Terrapin attack, aka CVE-2023-48795. If so,
  2367. * return a string describing the vulnerable thing. */
  2368. static const char *terrapin_vulnerable(
  2369. bool strict_kex, const transport_direction *d)
  2370. {
  2371. /*
  2372. * Strict kex mode eliminates the vulnerability. (That's what it's
  2373. * for.)
  2374. */
  2375. if (strict_kex)
  2376. return NULL;
  2377. /*
  2378. * ChaCha20-Poly1305 is vulnerable and perfectly exploitable.
  2379. */
  2380. if (d->cipher == &ssh2_chacha20_poly1305)
  2381. return "ChaCha20-Poly1305";
  2382. /*
  2383. * CBC-mode ciphers with OpenSSH's ETM modification are vulnerable
  2384. * and probabilistically exploitable.
  2385. */
  2386. if (d->etm_mode && (d->cipher->flags & SSH_CIPHER_IS_CBC))
  2387. return "a CBC-mode cipher in OpenSSH ETM mode";
  2388. return NULL;
  2389. }
  2390. /*
  2391. * Called when we've detected that at least one transport direction
  2392. * has the Terrapin vulnerability.
  2393. *
  2394. * Before we report it, try to replay what would have happened if the
  2395. * user had reconfigured their cipher settings to demote
  2396. * ChaCha20+Poly1305 to below the warning threshold. If that would
  2397. * have avoided the vulnerability, we should say so in the dialog box.
  2398. *
  2399. * This is basically the only change in PuTTY's configuration that has
  2400. * a chance of avoiding the problem. Terrapin affects the modified
  2401. * binary packet protocol used with ChaCha20+Poly1305, and also
  2402. * CBC-mode ciphers in ETM mode. But PuTTY unconditionally offers the
  2403. * ETM mode of each MAC _after_ the non-ETM mode. So the latter case
  2404. * can only come up if the server has been configured to _only_ permit
  2405. * the ETM modes of those MACs, which means there's nothing we can do
  2406. * anyway.
  2407. */
  2408. static bool try_to_avoid_terrapin(const struct ssh2_transport_state *s)
  2409. {
  2410. bool avoidable = false;
  2411. strbuf *alt_client_kexinit = strbuf_new();
  2412. Conf *alt_conf = conf_copy(s->conf);
  2413. struct kexinit_algorithm_list alt_kexlists[NKEXLIST];
  2414. memset(alt_kexlists, 0, sizeof(alt_kexlists));
  2415. /*
  2416. * We only bother doing this if we're the client, because Uppity
  2417. * can't present a dialog box anyway.
  2418. */
  2419. if (s->ssc)
  2420. goto out;
  2421. /*
  2422. * Demote CIPHER_CHACHA20 to just below CIPHER_WARN, if it was
  2423. * previously above it. If not, don't do anything - we don't want
  2424. * to _promote_ it.
  2425. */
  2426. { // WINSCP
  2427. int ccp_pos_now = -1, ccp_pos_wanted = -1;
  2428. int i; // WINSCP
  2429. for (i = 0; i < CIPHER_MAX; i++) {
  2430. switch (conf_get_int_int(alt_conf, CONF_ssh_cipherlist,
  2431. i)) {
  2432. case CIPHER_CHACHA20:
  2433. ccp_pos_now = i;
  2434. break;
  2435. case CIPHER_WARN:
  2436. ccp_pos_wanted = i;
  2437. break;
  2438. }
  2439. }
  2440. if (ccp_pos_now < 0 || ccp_pos_wanted < 0)
  2441. goto out; /* shouldn't ever happen: didn't find the two entries */
  2442. if (ccp_pos_now >= ccp_pos_wanted)
  2443. goto out; /* ChaCha20 is already demoted and it didn't help */
  2444. while (ccp_pos_now < ccp_pos_wanted) {
  2445. int cnext = conf_get_int_int(alt_conf, CONF_ssh_cipherlist,
  2446. ccp_pos_now + 1);
  2447. conf_set_int_int(alt_conf, CONF_ssh_cipherlist,
  2448. ccp_pos_now, cnext);
  2449. ccp_pos_now++;
  2450. }
  2451. conf_set_int_int(alt_conf, CONF_ssh_cipherlist,
  2452. ccp_pos_now + 1, CIPHER_CHACHA20);
  2453. } // WINSCP
  2454. /*
  2455. * Make the outgoing KEXINIT we would have made using this
  2456. * configuration.
  2457. */
  2458. put_byte(alt_client_kexinit, SSH2_MSG_KEXINIT);
  2459. put_padding(alt_client_kexinit, 16, 'x'); /* fake random padding */
  2460. ssh2_write_kexinit_lists(
  2461. /*WINSCP*/ s->ppl.seat, BinarySink_UPCAST(alt_client_kexinit), alt_kexlists, alt_conf,
  2462. s->ssc, s->ppl.remote_bugs, s->savedhost, s->savedport, s->hostkey_alg,
  2463. s->thc, s->host_cas, s->hostkeys, s->nhostkeys, !s->got_session_id,
  2464. s->can_gssapi_keyex,
  2465. s->gss_kex_used && !s->need_gss_transient_hostkey);
  2466. put_bool(alt_client_kexinit, false); /* guess packet follows */
  2467. put_uint32(alt_client_kexinit, 0); /* reserved */
  2468. /*
  2469. * Re-analyse the incoming KEXINIT with respect to this one, to
  2470. * see what we'd have decided on.
  2471. */
  2472. { // WINSCP
  2473. transport_direction cstrans, sctrans;
  2474. bool warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  2475. bool can_send_ext_info = false, strict_kex = false;
  2476. unsigned hkflags;
  2477. const ssh_kex *kex_alg;
  2478. const ssh_keyalg *hostkey_alg;
  2479. ScanKexinitsResult skr = ssh2_scan_kexinits(
  2480. ptrlen_from_strbuf(alt_client_kexinit),
  2481. ptrlen_from_strbuf(s->server_kexinit),
  2482. s->ssc != NULL, alt_kexlists, &kex_alg, &hostkey_alg,
  2483. &cstrans, &sctrans,
  2484. &warn_kex, &warn_hk, &warn_cscipher, &warn_sccipher, NULL, NULL, NULL,
  2485. &hkflags, &can_send_ext_info, !s->got_session_id, &strict_kex);
  2486. if (!skr.success) /* something else would have gone wrong */
  2487. goto out;
  2488. /*
  2489. * Reject this as an alternative solution if any of the warn flags
  2490. * has got worse, or if there's still anything
  2491. * Terrapin-vulnerable.
  2492. */
  2493. if (warn_kex > s->warn_kex)
  2494. goto out;
  2495. if (warn_hk > s->warn_hk)
  2496. goto out;
  2497. if (warn_cscipher > s->warn_cscipher)
  2498. goto out;
  2499. if (warn_sccipher > s->warn_sccipher)
  2500. goto out;
  2501. if (terrapin_vulnerable(strict_kex, &cstrans))
  2502. goto out;
  2503. if (terrapin_vulnerable(strict_kex, &sctrans))
  2504. goto out;
  2505. /*
  2506. * Success! The vulnerability could have been avoided by this Conf
  2507. * tweak, and we should tell the user so.
  2508. */
  2509. avoidable = true;
  2510. out:
  2511. { // WINSCP
  2512. size_t i;
  2513. for (i = 0; i < NKEXLIST; i++)
  2514. sfree(alt_kexlists[i].algs);
  2515. strbuf_free(alt_client_kexinit);
  2516. conf_free(alt_conf);
  2517. return avoidable;
  2518. } // WINSCP
  2519. } // WINSCP
  2520. }
  2521. #include "puttyexp.h"
  2522. static unsigned int ssh2_transport_winscp_query(PacketProtocolLayer *ppl, int query)
  2523. {
  2524. struct ssh2_transport_state *s =
  2525. container_of(ppl, struct ssh2_transport_state, ppl);
  2526. if (query == WINSCP_QUERY_TIMER)
  2527. {
  2528. ssh2_transport_timer(s, GETTICKCOUNT());
  2529. return 1;
  2530. }
  2531. else if (s->higher_layer->vt->winscp_query != NULL)
  2532. {
  2533. return ssh_ppl_winscp_query(s->higher_layer, query);
  2534. }
  2535. else
  2536. {
  2537. return 0;
  2538. }
  2539. }
  2540. void call_ssh_timer(Backend * be)
  2541. {
  2542. // TODO
  2543. }
  2544. // WINSCP
  2545. void get_hostkey_algs(int type, int * count, cp_ssh_keyalg ** sign_keys)
  2546. {
  2547. int i;
  2548. int max = lenof(ssh2_hostkey_algs);
  2549. *count = 0;
  2550. *sign_keys = snewn(max, cp_ssh_keyalg *);
  2551. for (i = 0; i < max; i++)
  2552. {
  2553. if ((type < 0) || (ssh2_hostkey_algs[i].id == type))
  2554. {
  2555. *((*sign_keys) + (*count)) = ssh2_hostkey_algs[i].alg;
  2556. (*count)++;
  2557. }
  2558. }
  2559. }
  2560. // WINSCP
  2561. void get_macs(int * count, const struct ssh2_macalg *** amacs)
  2562. {
  2563. *amacs = macs;
  2564. *count = lenof(macs);
  2565. }
  2566. int have_any_ssh2_hostkey(Seat * seat, const char * host, int port)
  2567. {
  2568. int j;
  2569. for (j = 0; j < lenof(ssh2_hostkey_algs); j++)
  2570. {
  2571. if (have_ssh_host_key(seat, host, port, ssh2_hostkey_algs[j].alg->cache_id))
  2572. {
  2573. return 1;
  2574. }
  2575. }
  2576. return 0;
  2577. }