ssh2transport.c 72 KB

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