ssh2transport.c 70 KB

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