ssh2transport.c 79 KB

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