ssh2transport.c 72 KB

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