transport2.c 88 KB

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