ssh2transport.c 70 KB

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