ssh2transport.c 73 KB

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