ssh2transport.c 74 KB

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