ssh2transport.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021
  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. #ifndef NO_GSSAPI
  12. #include "sshgssc.h"
  13. #include "sshgss.h"
  14. #define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */
  15. #define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */
  16. #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
  17. #define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
  18. #define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
  19. #endif
  20. #define DH_MIN_SIZE 1024
  21. #define DH_MAX_SIZE 8192
  22. enum kexlist {
  23. KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
  24. KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
  25. NKEXLIST
  26. };
  27. #define MAXKEXLIST 16
  28. struct kexinit_algorithm {
  29. const char *name;
  30. union {
  31. struct {
  32. const struct ssh_kex *kex;
  33. int warn;
  34. } kex;
  35. struct {
  36. const ssh_keyalg *hostkey;
  37. int warn;
  38. } hk;
  39. struct {
  40. const struct ssh2_cipheralg *cipher;
  41. int warn;
  42. } cipher;
  43. struct {
  44. const struct ssh2_macalg *mac;
  45. int etm;
  46. } mac;
  47. const struct ssh_compression_alg *comp;
  48. } u;
  49. };
  50. struct ssh_signkey_with_user_pref_id {
  51. const ssh_keyalg *alg;
  52. int id;
  53. };
  54. const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
  55. { &ssh_ecdsa_ed25519, HK_ED25519 },
  56. { &ssh_ecdsa_nistp256, HK_ECDSA },
  57. { &ssh_ecdsa_nistp384, HK_ECDSA },
  58. { &ssh_ecdsa_nistp521, HK_ECDSA },
  59. /* Changed order to match WinSCP default preference list for SshHostKeyList() */
  60. { &ssh_rsa, HK_RSA },
  61. { &ssh_dss, HK_DSA },
  62. };
  63. const static struct ssh2_macalg *const macs[] = {
  64. &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  65. };
  66. const static struct ssh2_macalg *const buggymacs[] = {
  67. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  68. };
  69. static ssh_compressor *ssh_comp_none_init(void)
  70. {
  71. return NULL;
  72. }
  73. static void ssh_comp_none_cleanup(ssh_compressor *handle)
  74. {
  75. }
  76. static ssh_decompressor *ssh_decomp_none_init(void)
  77. {
  78. return NULL;
  79. }
  80. static void ssh_decomp_none_cleanup(ssh_decompressor *handle)
  81. {
  82. }
  83. static void ssh_comp_none_block(ssh_compressor *handle,
  84. unsigned char *block, int len,
  85. unsigned char **outblock, int *outlen,
  86. int minlen)
  87. {
  88. }
  89. static int ssh_decomp_none_block(ssh_decompressor *handle,
  90. unsigned char *block, int len,
  91. unsigned char **outblock, int *outlen)
  92. {
  93. return 0;
  94. }
  95. const static struct ssh_compression_alg ssh_comp_none = {
  96. "none", NULL,
  97. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  98. ssh_decomp_none_init, ssh_decomp_none_cleanup, ssh_decomp_none_block,
  99. NULL
  100. };
  101. const static struct ssh_compression_alg *const compressions[] = {
  102. &ssh_zlib, &ssh_comp_none
  103. };
  104. /*
  105. * Enumeration of high-level classes of reason why we might need to do
  106. * a repeat key exchange. A full detailed reason in human-readable
  107. * string form for the Event Log is also provided, but this enum type
  108. * is used to discriminate between classes of reason that the code
  109. * needs to treat differently.
  110. *
  111. * RK_NONE == 0 is the value indicating that no rekey is currently
  112. * needed at all. RK_INITIAL indicates that we haven't even done the
  113. * _first_ key exchange yet. RK_SERVER indicates that we're rekeying
  114. * because the server asked for it, not because we decided it
  115. * ourselves. RK_NORMAL is the usual case. RK_GSS_UPDATE indicates
  116. * that we're rekeying because we've just got new GSSAPI credentials
  117. * (hence there's no point in doing a preliminary check for new GSS
  118. * creds, because we already know the answer); RK_POST_USERAUTH
  119. * indicates that _if_ we're going to need a post-userauth immediate
  120. * rekey for any reason, this is the moment to do it.
  121. *
  122. * So RK_POST_USERAUTH only tells the transport layer to _consider_
  123. * rekeying, not to definitely do it. Also, that one enum value is
  124. * special in that the user-readable reason text is passed in to the
  125. * transport layer as NULL, whereas fills in the reason text after it
  126. * decides whether it needs a rekey at all. In the other cases,
  127. * rekey_reason is passed in to the at the same time as rekey_class.
  128. */
  129. typedef enum RekeyClass {
  130. RK_NONE = 0,
  131. RK_INITIAL,
  132. RK_SERVER,
  133. RK_NORMAL,
  134. RK_POST_USERAUTH,
  135. RK_GSS_UPDATE
  136. } RekeyClass;
  137. struct ssh2_transport_state {
  138. int crState;
  139. PacketProtocolLayer *higher_layer;
  140. PktInQueue pq_in_higher;
  141. PktOutQueue pq_out_higher;
  142. IdempotentCallback ic_pq_out_higher;
  143. Conf *conf;
  144. char *savedhost;
  145. int savedport;
  146. const char *rekey_reason;
  147. enum RekeyClass rekey_class;
  148. unsigned long max_data_size;
  149. const struct ssh_kex *kex_alg;
  150. const ssh_keyalg *hostkey_alg;
  151. char *hostkey_str; /* string representation, for easy checking in rekeys */
  152. unsigned char session_id[SSH2_KEX_MAX_HASH_LEN];
  153. int session_id_len;
  154. struct dh_ctx *dh_ctx;
  155. ssh_hash *exhash;
  156. struct DataTransferStats *stats;
  157. char *client_greeting, *server_greeting;
  158. int kex_in_progress;
  159. unsigned long next_rekey, last_rekey;
  160. const char *deferred_rekey_reason;
  161. int higher_layer_ok;
  162. /*
  163. * Fully qualified host name, which we need if doing GSSAPI.
  164. */
  165. char *fullhostname;
  166. /* shgss is outside the ifdef on purpose to keep APIs simple. If
  167. * NO_GSSAPI is not defined, then it's just an opaque structure
  168. * tag and the pointer will be NULL. */
  169. struct ssh_connection_shared_gss_state *shgss;
  170. #ifndef NO_GSSAPI
  171. int gss_status;
  172. time_t gss_cred_expiry; /* Re-delegate if newer */
  173. unsigned long gss_ctxt_lifetime; /* Re-delegate when short */
  174. tree234 *transient_hostkey_cache;
  175. #endif
  176. int gss_kex_used;
  177. int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  178. Bignum p, g, e, f, K;
  179. void *our_kexinit;
  180. int our_kexinitlen;
  181. int kex_init_value, kex_reply_value;
  182. const struct ssh2_macalg *const *maclist;
  183. int nmacs;
  184. struct {
  185. const struct ssh2_cipheralg *cipher;
  186. const struct ssh2_macalg *mac;
  187. int etm_mode;
  188. const struct ssh_compression_alg *comp;
  189. } in, out;
  190. ptrlen hostkeydata, sigdata;
  191. char *keystr, *fingerprint;
  192. ssh_key *hkey; /* actual host key */
  193. struct RSAKey *rsa_kex_key; /* for RSA kex */
  194. struct ec_key *ecdh_key; /* for ECDH kex */
  195. unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
  196. int n_preferred_kex;
  197. int can_gssapi_keyex;
  198. int need_gss_transient_hostkey;
  199. int warned_about_no_gss_transient_hostkey;
  200. const struct ssh_kexes *preferred_kex[KEX_MAX + 1]; /* +1 for GSSAPI */
  201. int n_preferred_hk;
  202. int preferred_hk[HK_MAX];
  203. int n_preferred_ciphers;
  204. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  205. const struct ssh_compression_alg *preferred_comp;
  206. int userauth_succeeded; /* for delayed compression */
  207. int pending_compression;
  208. int got_session_id;
  209. int dlgret;
  210. int guessok;
  211. int ignorepkt;
  212. struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
  213. #ifndef NO_GSSAPI
  214. Ssh_gss_buf gss_buf;
  215. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  216. Ssh_gss_stat gss_stat;
  217. Ssh_gss_buf mic;
  218. int init_token_sent;
  219. int complete_rcvd;
  220. int gss_delegate;
  221. #endif
  222. /*
  223. * List of host key algorithms for which we _don't_ have a stored
  224. * host key. These are indices into the main hostkey_algs[] array
  225. */
  226. int uncert_hostkeys[lenof(hostkey_algs)];
  227. int n_uncert_hostkeys;
  228. /*
  229. * Flag indicating that the current rekey is intended to finish
  230. * with a newly cross-certified host key.
  231. */
  232. int cross_certifying;
  233. PacketProtocolLayer ppl;
  234. };
  235. static void ssh2_transport_free(PacketProtocolLayer *);
  236. static void ssh2_transport_process_queue(PacketProtocolLayer *);
  237. static int ssh2_transport_get_specials(
  238. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx);
  239. static void ssh2_transport_special_cmd(PacketProtocolLayer *ppl,
  240. SessionSpecialCode code, int arg);
  241. static int ssh2_transport_want_user_input(PacketProtocolLayer *ppl);
  242. static void ssh2_transport_got_user_input(PacketProtocolLayer *ppl);
  243. static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf);
  244. static void ssh2_transport_dialog_callback(void *, int);
  245. static void ssh2_transport_set_max_data_size(struct ssh2_transport_state *s);
  246. static unsigned long sanitise_rekey_time(int rekey_time, unsigned long def);
  247. static void ssh2_transport_higher_layer_packet_callback(void *context);
  248. static unsigned int ssh2_transport_winscp_query(PacketProtocolLayer *ppl, int query);
  249. static const struct PacketProtocolLayerVtable ssh2_transport_vtable = {
  250. ssh2_transport_free,
  251. ssh2_transport_process_queue,
  252. ssh2_transport_get_specials,
  253. ssh2_transport_special_cmd,
  254. ssh2_transport_want_user_input,
  255. ssh2_transport_got_user_input,
  256. ssh2_transport_reconfigure,
  257. NULL, /* no protocol name for this layer */
  258. ssh2_transport_winscp_query,
  259. };
  260. #ifndef NO_GSSAPI
  261. static void ssh2_transport_gss_update(struct ssh2_transport_state *s,
  262. int definitely_rekeying);
  263. static void ssh_init_transient_hostkey_store(struct ssh2_transport_state *);
  264. static void ssh_cleanup_transient_hostkey_store(struct ssh2_transport_state *);
  265. static void ssh_store_transient_hostkey(
  266. struct ssh2_transport_state *s, ssh_key *key);
  267. static int ssh_verify_transient_hostkey(
  268. struct ssh2_transport_state *s, ssh_key *key);
  269. static int ssh_have_transient_hostkey(
  270. struct ssh2_transport_state *s, const ssh_keyalg *alg);
  271. static int ssh_have_any_transient_hostkey(
  272. struct ssh2_transport_state *s);
  273. #endif
  274. static int ssh2_transport_timer_update(struct ssh2_transport_state *s,
  275. unsigned long rekey_time);
  276. static const char *const kexlist_descr[NKEXLIST] = {
  277. "key exchange algorithm",
  278. "host key algorithm",
  279. "client-to-server cipher",
  280. "server-to-client cipher",
  281. "client-to-server MAC",
  282. "server-to-client MAC",
  283. "client-to-server compression method",
  284. "server-to-client compression method"
  285. };
  286. PacketProtocolLayer *ssh2_transport_new(
  287. Conf *conf, const char *host, int port, const char *fullhostname,
  288. const char *client_greeting, const char *server_greeting,
  289. struct ssh_connection_shared_gss_state *shgss,
  290. struct DataTransferStats *stats,
  291. PacketProtocolLayer *higher_layer)
  292. {
  293. struct ssh2_transport_state *s = snew(struct ssh2_transport_state);
  294. memset(s, 0, sizeof(*s));
  295. s->ppl.vt = &ssh2_transport_vtable;
  296. s->conf = conf_copy(conf);
  297. s->savedhost = dupstr(host);
  298. s->savedport = port;
  299. s->fullhostname = dupstr(fullhostname);
  300. s->shgss = shgss;
  301. s->client_greeting = dupstr(client_greeting);
  302. s->server_greeting = dupstr(server_greeting);
  303. s->stats = stats;
  304. pq_in_init(&s->pq_in_higher, higher_layer->frontend); // WINSCP
  305. pq_out_init(&s->pq_out_higher, higher_layer->frontend); // WINSCP
  306. s->pq_out_higher.pqb.ic = &s->ic_pq_out_higher;
  307. s->ic_pq_out_higher.fn = ssh2_transport_higher_layer_packet_callback;
  308. s->ic_pq_out_higher.ctx = &s->ppl;
  309. s->ic_pq_out_higher.set = get_frontend_callback_set(higher_layer->frontend);
  310. s->higher_layer = higher_layer;
  311. s->higher_layer->selfptr = &s->higher_layer;
  312. ssh_ppl_setup_queues(s->higher_layer, &s->pq_in_higher, &s->pq_out_higher);
  313. #ifndef NO_GSSAPI
  314. s->gss_cred_expiry = GSS_NO_EXPIRATION;
  315. s->shgss->srv_name = GSS_C_NO_NAME;
  316. s->shgss->ctx = NULL;
  317. ssh_init_transient_hostkey_store(s);
  318. #endif
  319. s->gss_kex_used = FALSE;
  320. ssh2_transport_set_max_data_size(s);
  321. return &s->ppl;
  322. }
  323. static void ssh2_transport_free(PacketProtocolLayer *ppl)
  324. {
  325. struct ssh2_transport_state *s =
  326. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  327. /*
  328. * As our last act before being freed, move any outgoing packets
  329. * off our higher layer's output queue on to our own output queue.
  330. * We might be being freed while the SSH connection is still alive
  331. * (because we're initiating shutdown from our end), in which case
  332. * we don't want those last few packets to get lost.
  333. *
  334. * (If our owner were to have already destroyed our output pq
  335. * before wanting to free us, then it would have to reset our
  336. * publicly visible out_pq field to NULL to inhibit this attempt.
  337. * But that's not how I expect the shutdown sequence to go in
  338. * practice.)
  339. */
  340. if (s->ppl.out_pq)
  341. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  342. conf_free(s->conf);
  343. ssh_ppl_free(s->higher_layer);
  344. pq_in_clear(&s->pq_in_higher);
  345. pq_out_clear(&s->pq_out_higher);
  346. sfree(s->savedhost);
  347. sfree(s->fullhostname);
  348. sfree(s->client_greeting);
  349. sfree(s->server_greeting);
  350. sfree(s->keystr);
  351. sfree(s->hostkey_str);
  352. sfree(s->fingerprint);
  353. if (s->hkey) {
  354. ssh_key_free(s->hkey);
  355. s->hkey = NULL;
  356. }
  357. if (s->f) freebn(s->f);
  358. if (s->p) freebn(s->p);
  359. if (s->g) freebn(s->g);
  360. if (s->K) freebn(s->K);
  361. if (s->dh_ctx)
  362. dh_cleanup(s->dh_ctx);
  363. if (s->rsa_kex_key)
  364. ssh_rsakex_freekey(s->rsa_kex_key);
  365. if (s->ecdh_key)
  366. ssh_ecdhkex_freekey(s->ecdh_key);
  367. if (s->exhash)
  368. ssh_hash_free(s->exhash);
  369. #ifndef NO_GSSAPI
  370. ssh_cleanup_transient_hostkey_store(s);
  371. #endif
  372. sfree(s);
  373. }
  374. /*
  375. * SSH-2 key derivation (RFC 4253 section 7.2).
  376. */
  377. static void ssh2_mkkey(
  378. struct ssh2_transport_state *s, strbuf *out,
  379. Bignum K, unsigned char *H, char chr, int keylen)
  380. {
  381. int hlen = s->kex_alg->hash->hlen;
  382. int keylen_padded;
  383. unsigned char *key;
  384. ssh_hash *h;
  385. if (keylen == 0)
  386. return;
  387. /*
  388. * Round the requested amount of key material up to a multiple of
  389. * the length of the hash we're using to make it. This makes life
  390. * simpler because then we can just write each hash output block
  391. * straight into the output buffer without fiddling about
  392. * truncating the last one. Since it's going into a strbuf, and
  393. * strbufs are always smemclr()ed on free, there's no need to
  394. * worry about leaving extra potentially-sensitive data in memory
  395. * that the caller didn't ask for.
  396. */
  397. keylen_padded = ((keylen + hlen - 1) / hlen) * hlen;
  398. out->len = 0;
  399. key = strbuf_append(out, keylen_padded);
  400. /* First hlen bytes. */
  401. h = ssh_hash_new(s->kex_alg->hash);
  402. if (!(s->ppl.remote_bugs & BUG_SSH2_DERIVEKEY))
  403. put_mp_ssh2(h, K);
  404. put_data(h, H, hlen);
  405. put_byte(h, chr);
  406. put_data(h, s->session_id, s->session_id_len);
  407. ssh_hash_final(h, key);
  408. /* Subsequent blocks of hlen bytes. */
  409. if (keylen_padded > hlen) {
  410. int offset;
  411. h = ssh_hash_new(s->kex_alg->hash);
  412. if (!(s->ppl.remote_bugs & BUG_SSH2_DERIVEKEY))
  413. put_mp_ssh2(h, K);
  414. put_data(h, H, hlen);
  415. for (offset = hlen; offset < keylen_padded; offset += hlen) {
  416. put_data(h, key + offset - hlen, hlen);
  417. { // WINSCP
  418. ssh_hash *h2 = ssh_hash_copy(h);
  419. ssh_hash_final(h2, key + offset);
  420. } // WINSCP
  421. }
  422. ssh_hash_free(h);
  423. }
  424. }
  425. /*
  426. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  427. * If the algorithm is already in the list, return a pointer to its
  428. * entry, otherwise return an entry from the end of the list.
  429. * This assumes that every time a particular name is passed in, it
  430. * comes from the same string constant. If this isn't true, this
  431. * function may need to be rewritten to use strcmp() instead.
  432. */
  433. static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
  434. *list, const char *name)
  435. {
  436. int i;
  437. for (i = 0; i < MAXKEXLIST; i++)
  438. if (list[i].name == NULL || list[i].name == name) {
  439. list[i].name = name;
  440. return &list[i];
  441. }
  442. assert(!"No space in KEXINIT list");
  443. return NULL;
  444. }
  445. int ssh2_common_filter_queue(PacketProtocolLayer *ppl)
  446. {
  447. static const char *const ssh2_disconnect_reasons[] = {
  448. NULL,
  449. "host not allowed to connect",
  450. "protocol error",
  451. "key exchange failed",
  452. "host authentication failed",
  453. "MAC error",
  454. "compression error",
  455. "service not available",
  456. "protocol version not supported",
  457. "host key not verifiable",
  458. "connection lost",
  459. "by application",
  460. "too many connections",
  461. "auth cancelled by user",
  462. "no more auth methods available",
  463. "illegal user name",
  464. };
  465. PktIn *pktin;
  466. ptrlen msg;
  467. int reason;
  468. while ((pktin = pq_peek(ppl->in_pq)) != NULL) {
  469. switch (pktin->type) {
  470. case SSH2_MSG_DISCONNECT:
  471. reason = get_uint32(pktin);
  472. msg = get_string(pktin);
  473. ssh_remote_error(
  474. ppl->ssh, "Server sent disconnect message\n"
  475. "type %d (%s):\n\"%.*s\"", reason,
  476. ((reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  477. ssh2_disconnect_reasons[reason] : "unknown"),
  478. PTRLEN_PRINTF(msg));
  479. return TRUE; /* indicate that we've been freed */
  480. case SSH2_MSG_DEBUG:
  481. /* XXX maybe we should actually take notice of the return value */
  482. get_bool(pktin);
  483. msg = get_string(pktin);
  484. ppl_logevent(("Remote debug message: %.*s", PTRLEN_PRINTF(msg)));
  485. pq_pop(ppl->in_pq);
  486. break;
  487. case SSH2_MSG_IGNORE:
  488. /* Do nothing, because we're ignoring it! Duhh. */
  489. pq_pop(ppl->in_pq);
  490. break;
  491. default:
  492. return FALSE;
  493. }
  494. }
  495. return FALSE;
  496. }
  497. static int ssh2_transport_filter_queue(struct ssh2_transport_state *s)
  498. {
  499. PktIn *pktin;
  500. while (1) {
  501. if (ssh2_common_filter_queue(&s->ppl))
  502. return TRUE;
  503. if ((pktin = pq_peek(s->ppl.in_pq)) == NULL)
  504. return FALSE;
  505. /* Pass on packets to the next layer if they're outside
  506. * the range reserved for the transport protocol. */
  507. if (pktin->type >= 50) {
  508. /* ... except that we shouldn't tolerate higher-layer
  509. * packets coming from the server before we've seen
  510. * the first NEWKEYS. */
  511. if (!s->higher_layer_ok) {
  512. ssh_proto_error(s->ppl.ssh, "Received premature higher-"
  513. "layer packet, type %d (%s)", pktin->type,
  514. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  515. s->ppl.bpp->pls->actx,
  516. pktin->type));
  517. return TRUE;
  518. }
  519. pq_pop(s->ppl.in_pq);
  520. pq_push(&s->pq_in_higher, pktin);
  521. } else {
  522. /* Anything else is a transport-layer packet that the main
  523. * process_queue coroutine should handle. */
  524. return FALSE;
  525. }
  526. }
  527. }
  528. static PktIn *ssh2_transport_pop(struct ssh2_transport_state *s)
  529. {
  530. ssh2_transport_filter_queue(s);
  531. return pq_pop(s->ppl.in_pq);
  532. }
  533. static void ssh2_transport_process_queue(PacketProtocolLayer *ppl)
  534. {
  535. struct ssh2_transport_state *s =
  536. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  537. PktIn *pktin;
  538. PktOut *pktout;
  539. /* Filter centrally handled messages off the front of the queue on
  540. * every entry to this coroutine, no matter where we're resuming
  541. * from, even if we're _not_ looping on pq_pop. That way we can
  542. * still proactively handle those messages even if we're waiting
  543. * for a user response. */
  544. ssh2_transport_filter_queue(s);
  545. crBegin(s->crState);
  546. s->in.cipher = s->out.cipher = NULL;
  547. s->in.mac = s->out.mac = NULL;
  548. s->in.comp = s->out.comp = NULL;
  549. s->got_session_id = FALSE;
  550. s->userauth_succeeded = FALSE;
  551. s->pending_compression = FALSE;
  552. s->need_gss_transient_hostkey = FALSE;
  553. s->warned_about_no_gss_transient_hostkey = FALSE;
  554. /*
  555. * Be prepared to work around the buggy MAC problem.
  556. */
  557. if (s->ppl.remote_bugs & BUG_SSH2_HMAC)
  558. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  559. else
  560. s->maclist = macs, s->nmacs = lenof(macs);
  561. begin_key_exchange:
  562. #ifndef NO_GSSAPI
  563. if (s->need_gss_transient_hostkey) {
  564. /*
  565. * This flag indicates a special case in which we must not do
  566. * GSS key exchange even if we could. (See comments below,
  567. * where the flag was set on the previous key exchange.)
  568. */
  569. s->can_gssapi_keyex = FALSE;
  570. } else if (conf_get_int(s->conf, CONF_try_gssapi_kex)) {
  571. /*
  572. * We always check if we have GSS creds before we come up with
  573. * the kex algorithm list, otherwise future rekeys will fail
  574. * when creds expire. To make this so, this code section must
  575. * follow the begin_key_exchange label above, otherwise this
  576. * section would execute just once per-connection.
  577. *
  578. * Update GSS state unless the reason we're here is that a
  579. * timer just checked the GSS state and decided that we should
  580. * rekey to update delegated credentials. In that case, the
  581. * state is "fresh".
  582. */
  583. if (s->rekey_class != RK_GSS_UPDATE)
  584. ssh2_transport_gss_update(s, TRUE);
  585. /* Do GSSAPI KEX when capable */
  586. s->can_gssapi_keyex = s->gss_status & GSS_KEX_CAPABLE;
  587. /*
  588. * But not when failure is likely. [ GSS implementations may
  589. * attempt (and fail) to use a ticket that is almost expired
  590. * when retrieved from the ccache that actually expires by the
  591. * time the server receives it. ]
  592. *
  593. * Note: The first time always try KEXGSS if we can, failures
  594. * will be very rare, and disabling the initial GSS KEX is
  595. * worse. Some day GSS libraries will ignore cached tickets
  596. * whose lifetime is critically short, and will instead use
  597. * fresh ones.
  598. */
  599. if (!s->got_session_id && (s->gss_status & GSS_CTXT_MAYFAIL) != 0)
  600. s->can_gssapi_keyex = 0;
  601. s->gss_delegate = conf_get_int(s->conf, CONF_gssapifwd);
  602. } else {
  603. s->can_gssapi_keyex = FALSE;
  604. }
  605. #endif
  606. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_NOKEX;
  607. {
  608. int i, j, k, warn;
  609. struct kexinit_algorithm *alg;
  610. /*
  611. * Set up the preferred key exchange. (NULL => warn below here)
  612. */
  613. s->n_preferred_kex = 0;
  614. if (s->can_gssapi_keyex)
  615. s->preferred_kex[s->n_preferred_kex++] = &ssh_gssk5_sha1_kex;
  616. for (i = 0; i < KEX_MAX; i++) {
  617. switch (conf_get_int_int(s->conf, CONF_ssh_kexlist, i)) {
  618. case KEX_DHGEX:
  619. s->preferred_kex[s->n_preferred_kex++] =
  620. &ssh_diffiehellman_gex;
  621. break;
  622. case KEX_DHGROUP14:
  623. s->preferred_kex[s->n_preferred_kex++] =
  624. &ssh_diffiehellman_group14;
  625. break;
  626. case KEX_DHGROUP1:
  627. s->preferred_kex[s->n_preferred_kex++] =
  628. &ssh_diffiehellman_group1;
  629. break;
  630. case KEX_RSA:
  631. s->preferred_kex[s->n_preferred_kex++] =
  632. &ssh_rsa_kex;
  633. break;
  634. case KEX_ECDH:
  635. s->preferred_kex[s->n_preferred_kex++] =
  636. &ssh_ecdh_kex;
  637. break;
  638. case KEX_WARN:
  639. /* Flag for later. Don't bother if it's the last in
  640. * the list. */
  641. if (i < KEX_MAX - 1) {
  642. s->preferred_kex[s->n_preferred_kex++] = NULL;
  643. }
  644. break;
  645. }
  646. }
  647. /*
  648. * Set up the preferred host key types. These are just the ids
  649. * in the enum in putty.h, so 'warn below here' is indicated
  650. * by HK_WARN.
  651. */
  652. s->n_preferred_hk = 0;
  653. for (i = 0; i < HK_MAX; i++) {
  654. int id = conf_get_int_int(s->conf, CONF_ssh_hklist, i);
  655. /* As above, don't bother with HK_WARN if it's last in the
  656. * list */
  657. if (id != HK_WARN || i < HK_MAX - 1)
  658. s->preferred_hk[s->n_preferred_hk++] = id;
  659. }
  660. /*
  661. * Set up the preferred ciphers. (NULL => warn below here)
  662. */
  663. s->n_preferred_ciphers = 0;
  664. for (i = 0; i < CIPHER_MAX; i++) {
  665. switch (conf_get_int_int(s->conf, CONF_ssh_cipherlist, i)) {
  666. case CIPHER_BLOWFISH:
  667. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  668. break;
  669. case CIPHER_DES:
  670. if (conf_get_int(s->conf, CONF_ssh2_des_cbc))
  671. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  672. break;
  673. case CIPHER_3DES:
  674. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  675. break;
  676. case CIPHER_AES:
  677. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  678. break;
  679. case CIPHER_ARCFOUR:
  680. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
  681. break;
  682. case CIPHER_CHACHA20:
  683. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
  684. break;
  685. case CIPHER_WARN:
  686. /* Flag for later. Don't bother if it's the last in
  687. * the list. */
  688. if (i < CIPHER_MAX - 1) {
  689. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  690. }
  691. break;
  692. }
  693. }
  694. /*
  695. * Set up preferred compression.
  696. */
  697. if (conf_get_int(s->conf, CONF_compression))
  698. s->preferred_comp = &ssh_zlib;
  699. else
  700. s->preferred_comp = &ssh_comp_none;
  701. /*
  702. * Flag that KEX is in progress.
  703. */
  704. s->kex_in_progress = TRUE;
  705. for (i = 0; i < NKEXLIST; i++)
  706. for (j = 0; j < MAXKEXLIST; j++)
  707. s->kexlists[i][j].name = NULL;
  708. /* List key exchange algorithms. */
  709. warn = FALSE;
  710. for (i = 0; i < s->n_preferred_kex; i++) {
  711. const struct ssh_kexes *k = s->preferred_kex[i];
  712. if (!k) warn = TRUE;
  713. else for (j = 0; j < k->nkexes; j++) {
  714. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
  715. k->list[j]->name);
  716. alg->u.kex.kex = k->list[j];
  717. alg->u.kex.warn = warn;
  718. }
  719. }
  720. /* List server host key algorithms. */
  721. if (!s->got_session_id) {
  722. /*
  723. * In the first key exchange, we list all the algorithms
  724. * we're prepared to cope with, but prefer those algorithms
  725. * for which we have a host key for this host.
  726. *
  727. * If the host key algorithm is below the warning
  728. * threshold, we warn even if we did already have a key
  729. * for it, on the basis that if the user has just
  730. * reconfigured that host key type to be warned about,
  731. * they surely _do_ want to be alerted that a server
  732. * they're actually connecting to is using it.
  733. */
  734. warn = FALSE;
  735. for (i = 0; i < s->n_preferred_hk; i++) {
  736. if (s->preferred_hk[i] == HK_WARN)
  737. warn = TRUE;
  738. for (j = 0; j < lenof(hostkey_algs); j++) {
  739. if (hostkey_algs[j].id != s->preferred_hk[i])
  740. continue;
  741. if (have_ssh_host_key(
  742. s->ppl.frontend, // WINSCP
  743. s->savedhost, s->savedport,
  744. hostkey_algs[j].alg->cache_id)) {
  745. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  746. hostkey_algs[j].alg->ssh_id);
  747. alg->u.hk.hostkey = hostkey_algs[j].alg;
  748. alg->u.hk.warn = warn;
  749. }
  750. }
  751. }
  752. warn = FALSE;
  753. for (i = 0; i < s->n_preferred_hk; i++) {
  754. if (s->preferred_hk[i] == HK_WARN)
  755. warn = TRUE;
  756. for (j = 0; j < lenof(hostkey_algs); j++) {
  757. if (hostkey_algs[j].id != s->preferred_hk[i])
  758. continue;
  759. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  760. hostkey_algs[j].alg->ssh_id);
  761. alg->u.hk.hostkey = hostkey_algs[j].alg;
  762. alg->u.hk.warn = warn;
  763. }
  764. }
  765. #ifndef NO_GSSAPI
  766. } else if (s->gss_kex_used && !s->need_gss_transient_hostkey) {
  767. /*
  768. * If we've previously done a GSSAPI KEX, then we list
  769. * precisely the algorithms for which a previous GSS key
  770. * exchange has delivered us a host key, because we expect
  771. * one of exactly those keys to be used in any subsequent
  772. * non-GSS-based rekey.
  773. *
  774. * An exception is if this is the key exchange we
  775. * triggered for the purposes of populating that cache -
  776. * in which case the cache will currently be empty, which
  777. * isn't helpful!
  778. */
  779. warn = FALSE;
  780. for (i = 0; i < s->n_preferred_hk; i++) {
  781. if (s->preferred_hk[i] == HK_WARN)
  782. warn = TRUE;
  783. for (j = 0; j < lenof(hostkey_algs); j++) {
  784. if (hostkey_algs[j].id != s->preferred_hk[i])
  785. continue;
  786. if (ssh_have_transient_hostkey(s, hostkey_algs[j].alg)) {
  787. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  788. hostkey_algs[j].alg->ssh_id);
  789. alg->u.hk.hostkey = hostkey_algs[j].alg;
  790. alg->u.hk.warn = warn;
  791. }
  792. }
  793. }
  794. #endif
  795. } else {
  796. /*
  797. * In subsequent key exchanges, we list only the kex
  798. * algorithm that was selected in the first key exchange,
  799. * so that we keep getting the same host key and hence
  800. * don't have to interrupt the user's session to ask for
  801. * reverification.
  802. */
  803. assert(s->kex_alg);
  804. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  805. s->hostkey_alg->ssh_id);
  806. alg->u.hk.hostkey = s->hostkey_alg;
  807. alg->u.hk.warn = FALSE;
  808. }
  809. if (s->can_gssapi_keyex) {
  810. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY], "null");
  811. alg->u.hk.hostkey = NULL;
  812. }
  813. /* List encryption algorithms (client->server then server->client). */
  814. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  815. warn = FALSE;
  816. #ifdef FUZZING
  817. alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
  818. alg->u.cipher.cipher = NULL;
  819. alg->u.cipher.warn = warn;
  820. #endif /* FUZZING */
  821. for (i = 0; i < s->n_preferred_ciphers; i++) {
  822. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  823. if (!c) warn = TRUE;
  824. else for (j = 0; j < c->nciphers; j++) {
  825. alg = ssh2_kexinit_addalg(s->kexlists[k],
  826. c->list[j]->name);
  827. alg->u.cipher.cipher = c->list[j];
  828. alg->u.cipher.warn = warn;
  829. }
  830. }
  831. }
  832. /* List MAC algorithms (client->server then server->client). */
  833. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  834. #ifdef FUZZING
  835. alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
  836. alg->u.mac.mac = NULL;
  837. alg->u.mac.etm = FALSE;
  838. #endif /* FUZZING */
  839. for (i = 0; i < s->nmacs; i++) {
  840. alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
  841. alg->u.mac.mac = s->maclist[i];
  842. alg->u.mac.etm = FALSE;
  843. }
  844. for (i = 0; i < s->nmacs; i++)
  845. /* For each MAC, there may also be an ETM version,
  846. * which we list second. */
  847. if (s->maclist[i]->etm_name) {
  848. alg = ssh2_kexinit_addalg(s->kexlists[j],
  849. s->maclist[i]->etm_name);
  850. alg->u.mac.mac = s->maclist[i];
  851. alg->u.mac.etm = TRUE;
  852. }
  853. }
  854. /* List client->server compression algorithms,
  855. * then server->client compression algorithms. (We use the
  856. * same set twice.) */
  857. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  858. assert(lenof(compressions) > 1);
  859. /* Prefer non-delayed versions */
  860. alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
  861. alg->u.comp = s->preferred_comp;
  862. /* We don't even list delayed versions of algorithms until
  863. * they're allowed to be used, to avoid a race. See the end of
  864. * this function. */
  865. if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
  866. alg = ssh2_kexinit_addalg(s->kexlists[j],
  867. s->preferred_comp->delayed_name);
  868. alg->u.comp = s->preferred_comp;
  869. }
  870. for (i = 0; i < lenof(compressions); i++) {
  871. const struct ssh_compression_alg *c = compressions[i];
  872. alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
  873. alg->u.comp = c;
  874. if (s->userauth_succeeded && c->delayed_name) {
  875. alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
  876. alg->u.comp = c;
  877. }
  878. }
  879. }
  880. /*
  881. * Construct and send our key exchange packet.
  882. */
  883. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEXINIT);
  884. for (i = 0; i < 16; i++)
  885. put_byte(pktout, (unsigned char) random_byte());
  886. for (i = 0; i < NKEXLIST; i++) {
  887. strbuf *list = strbuf_new();
  888. for (j = 0; j < MAXKEXLIST; j++) {
  889. if (s->kexlists[i][j].name == NULL) break;
  890. add_to_commasep(list, s->kexlists[i][j].name);
  891. }
  892. put_stringsb(pktout, list);
  893. }
  894. /* List client->server languages. Empty list. */
  895. put_stringz(pktout, "");
  896. /* List server->client languages. Empty list. */
  897. put_stringz(pktout, "");
  898. /* First KEX packet does _not_ follow, because we're not that brave. */
  899. put_bool(pktout, FALSE);
  900. /* Reserved. */
  901. put_uint32(pktout, 0);
  902. }
  903. s->our_kexinitlen = pktout->length - 5;
  904. s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
  905. memcpy(s->our_kexinit, pktout->data + 5, s->our_kexinitlen);
  906. pq_push(s->ppl.out_pq, pktout);
  907. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  908. /*
  909. * Now examine the other side's KEXINIT to see what we're up
  910. * to.
  911. */
  912. {
  913. ptrlen str;
  914. int i, j;
  915. if (pktin->type != SSH2_MSG_KEXINIT) {
  916. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  917. "expecting KEXINIT, type %d (%s)", pktin->type,
  918. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  919. s->ppl.bpp->pls->actx, pktin->type));
  920. return;
  921. }
  922. s->kex_alg = NULL;
  923. s->hostkey_alg = NULL;
  924. s->in.cipher = s->out.cipher = NULL;
  925. s->in.mac = s->out.mac = NULL;
  926. s->in.comp = s->out.comp = NULL;
  927. s->warn_kex = s->warn_hk = FALSE;
  928. s->warn_cscipher = s->warn_sccipher = FALSE;
  929. get_data(pktin, 16); /* skip garbage cookie */
  930. s->guessok = FALSE;
  931. for (i = 0; i < NKEXLIST; i++) {
  932. str = get_string(pktin);
  933. if (get_err(pktin)) {
  934. ssh_proto_error(s->ppl.ssh, "KEXINIT packet was incomplete");
  935. return;
  936. }
  937. /* If we've already selected a cipher which requires a
  938. * particular MAC, then just select that, and don't even
  939. * bother looking through the server's KEXINIT string for
  940. * MACs. */
  941. if (i == KEXLIST_CSMAC && s->out.cipher &&
  942. s->out.cipher->required_mac) {
  943. s->out.mac = s->out.cipher->required_mac;
  944. s->out.etm_mode = !!(s->out.mac->etm_name);
  945. goto matched;
  946. }
  947. if (i == KEXLIST_SCMAC && s->in.cipher &&
  948. s->in.cipher->required_mac) {
  949. s->in.mac = s->in.cipher->required_mac;
  950. s->in.etm_mode = !!(s->in.mac->etm_name);
  951. goto matched;
  952. }
  953. for (j = 0; j < MAXKEXLIST; j++) {
  954. struct kexinit_algorithm *alg = &s->kexlists[i][j];
  955. if (alg->name == NULL) break;
  956. if (in_commasep_string(alg->name, str.ptr, str.len)) {
  957. /* We've found a matching algorithm. */
  958. if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
  959. /* Check if we might need to ignore first kex pkt */
  960. if (j != 0 ||
  961. !first_in_commasep_string(alg->name,
  962. str.ptr, str.len))
  963. s->guessok = FALSE;
  964. }
  965. if (i == KEXLIST_KEX) {
  966. s->kex_alg = alg->u.kex.kex;
  967. s->warn_kex = alg->u.kex.warn;
  968. } else if (i == KEXLIST_HOSTKEY) {
  969. /*
  970. * Ignore an unexpected/inappropriate offer of "null",
  971. * we offer "null" when we're willing to use GSS KEX,
  972. * but it is only acceptable when GSSKEX is actually
  973. * selected.
  974. */
  975. if (alg->u.hk.hostkey == NULL &&
  976. s->kex_alg->main_type != KEXTYPE_GSS)
  977. continue;
  978. s->hostkey_alg = alg->u.hk.hostkey;
  979. s->warn_hk = alg->u.hk.warn;
  980. } else if (i == KEXLIST_CSCIPHER) {
  981. s->out.cipher = alg->u.cipher.cipher;
  982. s->warn_cscipher = alg->u.cipher.warn;
  983. } else if (i == KEXLIST_SCCIPHER) {
  984. s->in.cipher = alg->u.cipher.cipher;
  985. s->warn_sccipher = alg->u.cipher.warn;
  986. } else if (i == KEXLIST_CSMAC) {
  987. s->out.mac = alg->u.mac.mac;
  988. s->out.etm_mode = alg->u.mac.etm;
  989. } else if (i == KEXLIST_SCMAC) {
  990. s->in.mac = alg->u.mac.mac;
  991. s->in.etm_mode = alg->u.mac.etm;
  992. } else if (i == KEXLIST_CSCOMP) {
  993. s->out.comp = alg->u.comp;
  994. } else if (i == KEXLIST_SCCOMP) {
  995. s->in.comp = alg->u.comp;
  996. }
  997. goto matched;
  998. }
  999. /* Set a flag if there's a delayed compression option
  1000. * available for a compression method that we just
  1001. * failed to select the immediate version of. */
  1002. s->pending_compression = (
  1003. (i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
  1004. in_commasep_string(alg->u.comp->delayed_name,
  1005. str.ptr, str.len) &&
  1006. !s->userauth_succeeded);
  1007. }
  1008. ssh_sw_abort(s->ppl.ssh, "Couldn't agree a %s (available: %.*s)",
  1009. kexlist_descr[i], PTRLEN_PRINTF(str));
  1010. return;
  1011. matched:;
  1012. if (i == KEXLIST_HOSTKEY &&
  1013. !s->gss_kex_used &&
  1014. s->kex_alg->main_type != KEXTYPE_GSS) {
  1015. int j;
  1016. /*
  1017. * In addition to deciding which host key we're
  1018. * actually going to use, we should make a list of the
  1019. * host keys offered by the server which we _don't_
  1020. * have cached. These will be offered as cross-
  1021. * certification options by ssh_get_specials.
  1022. *
  1023. * We also count the key we're currently using for KEX
  1024. * as one we've already got, because by the time this
  1025. * menu becomes visible, it will be.
  1026. */
  1027. s->n_uncert_hostkeys = 0;
  1028. for (j = 0; j < lenof(hostkey_algs); j++) {
  1029. if (hostkey_algs[j].alg != s->hostkey_alg &&
  1030. in_commasep_string(hostkey_algs[j].alg->ssh_id,
  1031. str.ptr, str.len) &&
  1032. !have_ssh_host_key(
  1033. s->ppl.frontend, // WINSCP
  1034. s->savedhost, s->savedport,
  1035. hostkey_algs[j].alg->cache_id)) {
  1036. s->uncert_hostkeys[s->n_uncert_hostkeys++] = j;
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if (s->pending_compression) {
  1042. ppl_logevent(("Server supports delayed compression; "
  1043. "will try this later"));
  1044. }
  1045. get_string(pktin); /* client->server language */
  1046. get_string(pktin); /* server->client language */
  1047. s->ignorepkt = get_bool(pktin) && !s->guessok;
  1048. s->exhash = ssh_hash_new(s->kex_alg->hash);
  1049. put_stringz(s->exhash, s->client_greeting);
  1050. put_stringz(s->exhash, s->server_greeting);
  1051. put_string(s->exhash, s->our_kexinit, s->our_kexinitlen);
  1052. sfree(s->our_kexinit);
  1053. /* Include the type byte in the hash of server's KEXINIT */
  1054. put_string(s->exhash,
  1055. (const char *)BinarySource_UPCAST(pktin)->data - 1,
  1056. BinarySource_UPCAST(pktin)->len + 1);
  1057. if (s->warn_kex) {
  1058. s->dlgret = askalg(s->ppl.frontend, "key-exchange algorithm",
  1059. s->kex_alg->name,
  1060. ssh2_transport_dialog_callback, s);
  1061. crMaybeWaitUntilV(s->dlgret >= 0);
  1062. if (s->dlgret == 0) {
  1063. ssh_user_close(s->ppl.ssh, "User aborted at kex warning");
  1064. return;
  1065. }
  1066. }
  1067. if (s->warn_hk) {
  1068. int j, k;
  1069. char *betteralgs;
  1070. /*
  1071. * Change warning box wording depending on why we chose a
  1072. * warning-level host key algorithm. If it's because
  1073. * that's all we have *cached*, use the askhk mechanism,
  1074. * and list the host keys we could usefully cross-certify.
  1075. * Otherwise, use askalg for the standard wording.
  1076. */
  1077. betteralgs = NULL;
  1078. for (j = 0; j < s->n_uncert_hostkeys; j++) {
  1079. const struct ssh_signkey_with_user_pref_id *hktype =
  1080. &hostkey_algs[s->uncert_hostkeys[j]];
  1081. int better = FALSE;
  1082. for (k = 0; k < HK_MAX; k++) {
  1083. int id = conf_get_int_int(s->conf, CONF_ssh_hklist, k);
  1084. if (id == HK_WARN) {
  1085. break;
  1086. } else if (id == hktype->id) {
  1087. better = TRUE;
  1088. break;
  1089. }
  1090. }
  1091. if (better) {
  1092. if (betteralgs) {
  1093. char *old_ba = betteralgs;
  1094. betteralgs = dupcat(betteralgs, ",",
  1095. hktype->alg->ssh_id,
  1096. (const char *)NULL);
  1097. sfree(old_ba);
  1098. } else {
  1099. betteralgs = dupstr(hktype->alg->ssh_id);
  1100. }
  1101. }
  1102. }
  1103. if (betteralgs) {
  1104. s->dlgret = askhk(
  1105. s->ppl.frontend, s->hostkey_alg->ssh_id, betteralgs,
  1106. ssh2_transport_dialog_callback, s);
  1107. sfree(betteralgs);
  1108. } else {
  1109. s->dlgret = askalg(s->ppl.frontend, "host key type",
  1110. s->hostkey_alg->ssh_id,
  1111. ssh2_transport_dialog_callback, s);
  1112. }
  1113. crMaybeWaitUntilV(s->dlgret >= 0);
  1114. if (s->dlgret == 0) {
  1115. ssh_user_close(s->ppl.ssh, "User aborted at host key warning");
  1116. return;
  1117. }
  1118. }
  1119. if (s->warn_cscipher) {
  1120. s->dlgret = askalg(s->ppl.frontend,
  1121. "client-to-server cipher",
  1122. s->out.cipher->name,
  1123. ssh2_transport_dialog_callback, s);
  1124. crMaybeWaitUntilV(s->dlgret >= 0);
  1125. if (s->dlgret == 0) {
  1126. ssh_user_close(s->ppl.ssh, "User aborted at cipher warning");
  1127. return;
  1128. }
  1129. }
  1130. if (s->warn_sccipher) {
  1131. s->dlgret = askalg(s->ppl.frontend,
  1132. "server-to-client cipher",
  1133. s->in.cipher->name,
  1134. ssh2_transport_dialog_callback, s);
  1135. crMaybeWaitUntilV(s->dlgret >= 0);
  1136. if (s->dlgret == 0) {
  1137. ssh_user_close(s->ppl.ssh, "User aborted at cipher warning");
  1138. return;
  1139. }
  1140. }
  1141. if (s->ignorepkt) /* first_kex_packet_follows */
  1142. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1143. }
  1144. if (s->kex_alg->main_type == KEXTYPE_DH) {
  1145. /*
  1146. * Work out the number of bits of key we will need from the
  1147. * key exchange. We start with the maximum key length of
  1148. * either cipher...
  1149. */
  1150. {
  1151. int csbits, scbits;
  1152. csbits = s->out.cipher ? s->out.cipher->real_keybits : 0;
  1153. scbits = s->in.cipher ? s->in.cipher->real_keybits : 0;
  1154. s->nbits = (csbits > scbits ? csbits : scbits);
  1155. }
  1156. /* The keys only have hlen-bit entropy, since they're based on
  1157. * a hash. So cap the key size at hlen bits. */
  1158. if (s->nbits > s->kex_alg->hash->hlen * 8)
  1159. s->nbits = s->kex_alg->hash->hlen * 8;
  1160. /*
  1161. * If we're doing Diffie-Hellman group exchange, start by
  1162. * requesting a group.
  1163. */
  1164. if (dh_is_gex(s->kex_alg)) {
  1165. ppl_logevent(("Doing Diffie-Hellman group exchange"));
  1166. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_DHGEX;
  1167. /*
  1168. * Work out how big a DH group we will need to allow that
  1169. * much data.
  1170. */
  1171. s->pbits = 512 << ((s->nbits - 1) / 64);
  1172. if (s->pbits < DH_MIN_SIZE)
  1173. s->pbits = DH_MIN_SIZE;
  1174. if (s->pbits > DH_MAX_SIZE)
  1175. s->pbits = DH_MAX_SIZE;
  1176. if ((s->ppl.remote_bugs & BUG_SSH2_OLDGEX)) {
  1177. pktout = ssh_bpp_new_pktout(
  1178. s->ppl.bpp, SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
  1179. put_uint32(pktout, s->pbits);
  1180. } else {
  1181. pktout = ssh_bpp_new_pktout(
  1182. s->ppl.bpp, SSH2_MSG_KEX_DH_GEX_REQUEST);
  1183. put_uint32(pktout, DH_MIN_SIZE);
  1184. put_uint32(pktout, s->pbits);
  1185. put_uint32(pktout, DH_MAX_SIZE);
  1186. }
  1187. pq_push(s->ppl.out_pq, pktout);
  1188. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1189. if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  1190. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1191. "expecting Diffie-Hellman group, type %d (%s)",
  1192. pktin->type,
  1193. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1194. s->ppl.bpp->pls->actx,
  1195. pktin->type));
  1196. return;
  1197. }
  1198. s->p = get_mp_ssh2(pktin);
  1199. s->g = get_mp_ssh2(pktin);
  1200. if (get_err(pktin)) {
  1201. ssh_proto_error(s->ppl.ssh,
  1202. "Unable to parse Diffie-Hellman group packet");
  1203. return;
  1204. }
  1205. s->dh_ctx = dh_setup_gex(s->p, s->g);
  1206. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  1207. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  1208. } else {
  1209. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_DHGROUP;
  1210. s->dh_ctx = dh_setup_group(s->kex_alg);
  1211. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  1212. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  1213. ppl_logevent(("Using Diffie-Hellman with standard group \"%s\"",
  1214. s->kex_alg->groupname));
  1215. }
  1216. ppl_logevent(("Doing Diffie-Hellman key exchange with hash %s",
  1217. s->kex_alg->hash->text_name));
  1218. /*
  1219. * Now generate and send e for Diffie-Hellman.
  1220. */
  1221. set_busy_status(s->ppl.frontend, BUSY_CPU); /* this can take a while */
  1222. s->e = dh_create_e(s->dh_ctx, s->nbits * 2);
  1223. pktout = ssh_bpp_new_pktout(s->ppl.bpp, s->kex_init_value);
  1224. put_mp_ssh2(pktout, s->e);
  1225. pq_push(s->ppl.out_pq, pktout);
  1226. set_busy_status(s->ppl.frontend, BUSY_WAITING); /* wait for server */
  1227. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1228. if (pktin->type != s->kex_reply_value) {
  1229. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1230. "expecting Diffie-Hellman reply, type %d (%s)",
  1231. pktin->type,
  1232. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1233. s->ppl.bpp->pls->actx,
  1234. pktin->type));
  1235. return;
  1236. }
  1237. set_busy_status(s->ppl.frontend, BUSY_CPU); /* cogitate */
  1238. s->hostkeydata = get_string(pktin);
  1239. s->hkey = ssh_key_new_pub(s->hostkey_alg, s->hostkeydata);
  1240. s->f = get_mp_ssh2(pktin);
  1241. s->sigdata = get_string(pktin);
  1242. if (get_err(pktin)) {
  1243. ssh_proto_error(s->ppl.ssh,
  1244. "Unable to parse Diffie-Hellman reply packet");
  1245. return;
  1246. }
  1247. {
  1248. const char *err = dh_validate_f(s->dh_ctx, s->f);
  1249. if (err) {
  1250. ssh_proto_error(s->ppl.ssh, "Diffie-Hellman reply failed "
  1251. "validation: %s", err);
  1252. return;
  1253. }
  1254. }
  1255. s->K = dh_find_K(s->dh_ctx, s->f);
  1256. /* We assume everything from now on will be quick, and it might
  1257. * involve user interaction. */
  1258. set_busy_status(s->ppl.frontend, BUSY_NOT);
  1259. put_stringpl(s->exhash, s->hostkeydata);
  1260. if (dh_is_gex(s->kex_alg)) {
  1261. if (!(s->ppl.remote_bugs & BUG_SSH2_OLDGEX))
  1262. put_uint32(s->exhash, DH_MIN_SIZE);
  1263. put_uint32(s->exhash, s->pbits);
  1264. if (!(s->ppl.remote_bugs & BUG_SSH2_OLDGEX))
  1265. put_uint32(s->exhash, DH_MAX_SIZE);
  1266. put_mp_ssh2(s->exhash, s->p);
  1267. put_mp_ssh2(s->exhash, s->g);
  1268. }
  1269. put_mp_ssh2(s->exhash, s->e);
  1270. put_mp_ssh2(s->exhash, s->f);
  1271. dh_cleanup(s->dh_ctx);
  1272. s->dh_ctx = NULL;
  1273. freebn(s->f); s->f = NULL;
  1274. if (dh_is_gex(s->kex_alg)) {
  1275. freebn(s->g); s->g = NULL;
  1276. freebn(s->p); s->p = NULL;
  1277. }
  1278. } else if (s->kex_alg->main_type == KEXTYPE_ECDH) {
  1279. ppl_logevent(("Doing ECDH key exchange with curve %s and hash %s",
  1280. ssh_ecdhkex_curve_textname(s->kex_alg),
  1281. s->kex_alg->hash->text_name));
  1282. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_ECDHKEX;
  1283. s->ecdh_key = ssh_ecdhkex_newkey(s->kex_alg);
  1284. if (!s->ecdh_key) {
  1285. ssh_sw_abort(s->ppl.ssh, "Unable to generate key for ECDH");
  1286. return;
  1287. }
  1288. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEX_ECDH_INIT);
  1289. {
  1290. strbuf *pubpoint = strbuf_new();
  1291. ssh_ecdhkex_getpublic(s->ecdh_key, BinarySink_UPCAST(pubpoint));
  1292. put_stringsb(pktout, pubpoint);
  1293. }
  1294. pq_push(s->ppl.out_pq, pktout);
  1295. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1296. if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
  1297. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1298. "expecting ECDH reply, type %d (%s)", pktin->type,
  1299. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1300. s->ppl.bpp->pls->actx,
  1301. pktin->type));
  1302. return;
  1303. }
  1304. s->hostkeydata = get_string(pktin);
  1305. put_stringpl(s->exhash, s->hostkeydata);
  1306. s->hkey = ssh_key_new_pub(s->hostkey_alg, s->hostkeydata);
  1307. {
  1308. strbuf *pubpoint = strbuf_new();
  1309. ssh_ecdhkex_getpublic(s->ecdh_key, BinarySink_UPCAST(pubpoint));
  1310. put_string(s->exhash, pubpoint->u, pubpoint->len);
  1311. strbuf_free(pubpoint);
  1312. }
  1313. {
  1314. ptrlen keydata = get_string(pktin);
  1315. put_stringpl(s->exhash, keydata);
  1316. s->K = ssh_ecdhkex_getkey(s->ecdh_key, keydata.ptr, keydata.len);
  1317. if (!get_err(pktin) && !s->K) {
  1318. ssh_proto_error(s->ppl.ssh, "Received invalid elliptic curve "
  1319. "point in ECDH reply");
  1320. return;
  1321. }
  1322. }
  1323. s->sigdata = get_string(pktin);
  1324. if (get_err(pktin)) {
  1325. ssh_proto_error(s->ppl.ssh, "Unable to parse ECDH reply packet");
  1326. return;
  1327. }
  1328. ssh_ecdhkex_freekey(s->ecdh_key);
  1329. s->ecdh_key = NULL;
  1330. #ifndef NO_GSSAPI
  1331. } else if (s->kex_alg->main_type == KEXTYPE_GSS) {
  1332. ptrlen data;
  1333. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_GSSKEX;
  1334. s->init_token_sent = 0;
  1335. s->complete_rcvd = 0;
  1336. s->hkey = NULL;
  1337. s->fingerprint = NULL;
  1338. s->keystr = NULL;
  1339. /*
  1340. * Work out the number of bits of key we will need from the
  1341. * key exchange. We start with the maximum key length of
  1342. * either cipher...
  1343. *
  1344. * This is rote from the KEXTYPE_DH section above.
  1345. */
  1346. {
  1347. int csbits, scbits;
  1348. csbits = s->out.cipher->real_keybits;
  1349. scbits = s->in.cipher->real_keybits;
  1350. s->nbits = (csbits > scbits ? csbits : scbits);
  1351. }
  1352. /* The keys only have hlen-bit entropy, since they're based on
  1353. * a hash. So cap the key size at hlen bits. */
  1354. if (s->nbits > s->kex_alg->hash->hlen * 8)
  1355. s->nbits = s->kex_alg->hash->hlen * 8;
  1356. if (dh_is_gex(s->kex_alg)) {
  1357. /*
  1358. * Work out how big a DH group we will need to allow that
  1359. * much data.
  1360. */
  1361. s->pbits = 512 << ((s->nbits - 1) / 64);
  1362. ppl_logevent(("Doing GSSAPI (with Kerberos V5) Diffie-Hellman "
  1363. "group exchange, with minimum %d bits", s->pbits));
  1364. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEXGSS_GROUPREQ);
  1365. put_uint32(pktout, s->pbits); /* min */
  1366. put_uint32(pktout, s->pbits); /* preferred */
  1367. put_uint32(pktout, s->pbits * 2); /* max */
  1368. pq_push(s->ppl.out_pq, pktout);
  1369. crMaybeWaitUntilV(
  1370. (pktin = ssh2_transport_pop(s)) != NULL);
  1371. if (pktin->type != SSH2_MSG_KEXGSS_GROUP) {
  1372. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1373. "expecting Diffie-Hellman group, type %d (%s)",
  1374. pktin->type,
  1375. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1376. s->ppl.bpp->pls->actx,
  1377. pktin->type));
  1378. return;
  1379. }
  1380. s->p = get_mp_ssh2(pktin);
  1381. s->g = get_mp_ssh2(pktin);
  1382. if (get_err(pktin)) {
  1383. ssh_proto_error(s->ppl.ssh,
  1384. "Unable to parse Diffie-Hellman group packet");
  1385. return;
  1386. }
  1387. s->dh_ctx = dh_setup_gex(s->p, s->g);
  1388. } else {
  1389. s->dh_ctx = dh_setup_group(s->kex_alg);
  1390. ppl_logevent(("Using GSSAPI (with Kerberos V5) Diffie-Hellman with"
  1391. " standard group \"%s\"", s->kex_alg->groupname));
  1392. }
  1393. ppl_logevent(("Doing GSSAPI (with Kerberos V5) Diffie-Hellman key "
  1394. "exchange with hash %s", s->kex_alg->hash->text_name));
  1395. /* Now generate e for Diffie-Hellman. */
  1396. set_busy_status(s->ppl.frontend, BUSY_CPU); /* this can take a while */
  1397. s->e = dh_create_e(s->dh_ctx, s->nbits * 2);
  1398. if (s->shgss->lib->gsslogmsg)
  1399. ppl_logevent(("%s", s->shgss->lib->gsslogmsg));
  1400. /* initial tokens are empty */
  1401. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  1402. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  1403. SSH_GSS_CLEAR_BUF(&s->mic);
  1404. s->gss_stat = s->shgss->lib->acquire_cred(
  1405. s->shgss->lib, &s->shgss->ctx, &s->gss_cred_expiry);
  1406. if (s->gss_stat != SSH_GSS_OK) {
  1407. ssh_sw_abort(s->ppl.ssh,
  1408. "GSSAPI key exchange failed to initialise");
  1409. return;
  1410. }
  1411. /* now enter the loop */
  1412. assert(s->shgss->srv_name);
  1413. do {
  1414. /*
  1415. * When acquire_cred yields no useful expiration, go with the
  1416. * service ticket expiration.
  1417. */
  1418. s->gss_stat = s->shgss->lib->init_sec_context(
  1419. s->shgss->lib, &s->shgss->ctx, s->shgss->srv_name,
  1420. s->gss_delegate, &s->gss_rcvtok, &s->gss_sndtok,
  1421. (s->gss_cred_expiry == GSS_NO_EXPIRATION ?
  1422. &s->gss_cred_expiry : NULL), NULL);
  1423. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  1424. if (s->gss_stat == SSH_GSS_S_COMPLETE && s->complete_rcvd)
  1425. break; /* MIC is verified after the loop */
  1426. if (s->gss_stat != SSH_GSS_S_COMPLETE &&
  1427. s->gss_stat != SSH_GSS_S_CONTINUE_NEEDED) {
  1428. if (s->shgss->lib->display_status(
  1429. s->shgss->lib, s->shgss->ctx,
  1430. &s->gss_buf) == SSH_GSS_OK) {
  1431. char *err = s->gss_buf.value;
  1432. ssh_sw_abort(s->ppl.ssh,
  1433. "GSSAPI key exchange failed to initialise "
  1434. "context: %s", err);
  1435. sfree(err);
  1436. return;
  1437. }
  1438. }
  1439. assert(s->gss_stat == SSH_GSS_S_COMPLETE ||
  1440. s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  1441. if (!s->init_token_sent) {
  1442. s->init_token_sent = 1;
  1443. pktout = ssh_bpp_new_pktout(s->ppl.bpp,
  1444. SSH2_MSG_KEXGSS_INIT);
  1445. if (s->gss_sndtok.length == 0) {
  1446. ssh_sw_abort(s->ppl.ssh, "GSSAPI key exchange failed: "
  1447. "no initial context token");
  1448. return;
  1449. }
  1450. put_string(pktout,
  1451. s->gss_sndtok.value, s->gss_sndtok.length);
  1452. put_mp_ssh2(pktout, s->e);
  1453. pq_push(s->ppl.out_pq, pktout);
  1454. s->shgss->lib->free_tok(s->shgss->lib, &s->gss_sndtok);
  1455. ppl_logevent(("GSSAPI key exchange initialised"));
  1456. } else if (s->gss_sndtok.length != 0) {
  1457. pktout = ssh_bpp_new_pktout(
  1458. s->ppl.bpp, SSH2_MSG_KEXGSS_CONTINUE);
  1459. put_string(pktout,
  1460. s->gss_sndtok.value, s->gss_sndtok.length);
  1461. pq_push(s->ppl.out_pq, pktout);
  1462. s->shgss->lib->free_tok(s->shgss->lib, &s->gss_sndtok);
  1463. }
  1464. if (s->gss_stat == SSH_GSS_S_COMPLETE && s->complete_rcvd)
  1465. break;
  1466. wait_for_gss_token:
  1467. crMaybeWaitUntilV(
  1468. (pktin = ssh2_transport_pop(s)) != NULL);
  1469. switch (pktin->type) {
  1470. case SSH2_MSG_KEXGSS_CONTINUE:
  1471. data = get_string(pktin);
  1472. s->gss_rcvtok.value = (char *)data.ptr;
  1473. s->gss_rcvtok.length = data.len;
  1474. continue;
  1475. case SSH2_MSG_KEXGSS_COMPLETE:
  1476. s->complete_rcvd = 1;
  1477. s->f = get_mp_ssh2(pktin);
  1478. data = get_string(pktin);
  1479. s->mic.value = (char *)data.ptr;
  1480. s->mic.length = data.len;
  1481. /* Save expiration time of cred when delegating */
  1482. if (s->gss_delegate && s->gss_cred_expiry != GSS_NO_EXPIRATION)
  1483. s->gss_cred_expiry = s->gss_cred_expiry;
  1484. /* If there's a final token we loop to consume it */
  1485. if (get_bool(pktin)) {
  1486. data = get_string(pktin);
  1487. s->gss_rcvtok.value = (char *)data.ptr;
  1488. s->gss_rcvtok.length = data.len;
  1489. continue;
  1490. }
  1491. break;
  1492. case SSH2_MSG_KEXGSS_HOSTKEY:
  1493. s->hostkeydata = get_string(pktin);
  1494. if (s->hostkey_alg) {
  1495. s->hkey = ssh_key_new_pub(s->hostkey_alg,
  1496. s->hostkeydata);
  1497. put_string(s->exhash,
  1498. s->hostkeydata.ptr, s->hostkeydata.len);
  1499. }
  1500. /*
  1501. * Can't loop as we have no token to pass to
  1502. * init_sec_context.
  1503. */
  1504. goto wait_for_gss_token;
  1505. case SSH2_MSG_KEXGSS_ERROR:
  1506. /*
  1507. * We have no use for the server's major and minor
  1508. * status. The minor status is really only
  1509. * meaningful to the server, and with luck the major
  1510. * status means something to us (but not really all
  1511. * that much). The string is more meaningful, and
  1512. * hopefully the server sends any error tokens, as
  1513. * that will produce the most useful information for
  1514. * us.
  1515. */
  1516. get_uint32(pktin); /* server's major status */
  1517. get_uint32(pktin); /* server's minor status */
  1518. data = get_string(pktin);
  1519. ppl_logevent(("GSSAPI key exchange failed; "
  1520. "server's message: %.*s", PTRLEN_PRINTF(data)));
  1521. /* Language tag, but we have no use for it */
  1522. get_string(pktin);
  1523. /*
  1524. * Wait for an error token, if there is one, or the
  1525. * server's disconnect. The error token, if there
  1526. * is one, must follow the SSH2_MSG_KEXGSS_ERROR
  1527. * message, per the RFC.
  1528. */
  1529. goto wait_for_gss_token;
  1530. default:
  1531. ssh_proto_error(s->ppl.ssh, "Received unexpected packet "
  1532. "during GSSAPI key exchange, type %d (%s)",
  1533. pktin->type,
  1534. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1535. s->ppl.bpp->pls->actx,
  1536. pktin->type));
  1537. return;
  1538. }
  1539. } while (s->gss_rcvtok.length ||
  1540. s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED ||
  1541. !s->complete_rcvd);
  1542. s->K = dh_find_K(s->dh_ctx, s->f);
  1543. /* We assume everything from now on will be quick, and it might
  1544. * involve user interaction. */
  1545. set_busy_status(s->ppl.frontend, BUSY_NOT);
  1546. if (!s->hkey)
  1547. put_stringz(s->exhash, "");
  1548. if (dh_is_gex(s->kex_alg)) {
  1549. /* min, preferred, max */
  1550. put_uint32(s->exhash, s->pbits);
  1551. put_uint32(s->exhash, s->pbits);
  1552. put_uint32(s->exhash, s->pbits * 2);
  1553. put_mp_ssh2(s->exhash, s->p);
  1554. put_mp_ssh2(s->exhash, s->g);
  1555. }
  1556. put_mp_ssh2(s->exhash, s->e);
  1557. put_mp_ssh2(s->exhash, s->f);
  1558. /*
  1559. * MIC verification is done below, after we compute the hash
  1560. * used as the MIC input.
  1561. */
  1562. dh_cleanup(s->dh_ctx);
  1563. s->dh_ctx = NULL;
  1564. freebn(s->f); s->f = NULL;
  1565. if (dh_is_gex(s->kex_alg)) {
  1566. freebn(s->g); s->g = NULL;
  1567. freebn(s->p); s->p = NULL;
  1568. }
  1569. #endif
  1570. } else {
  1571. ptrlen rsakeydata;
  1572. assert(s->kex_alg->main_type == KEXTYPE_RSA);
  1573. ppl_logevent(("Doing RSA key exchange with hash %s",
  1574. s->kex_alg->hash->text_name));
  1575. s->ppl.bpp->pls->kctx = SSH2_PKTCTX_RSAKEX;
  1576. /*
  1577. * RSA key exchange. First expect a KEXRSA_PUBKEY packet
  1578. * from the server.
  1579. */
  1580. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1581. if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
  1582. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1583. "expecting RSA public key, type %d (%s)",
  1584. pktin->type,
  1585. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1586. s->ppl.bpp->pls->actx,
  1587. pktin->type));
  1588. return;
  1589. }
  1590. s->hostkeydata = get_string(pktin);
  1591. put_stringpl(s->exhash, s->hostkeydata);
  1592. s->hkey = ssh_key_new_pub(s->hostkey_alg, s->hostkeydata);
  1593. rsakeydata = get_string(pktin);
  1594. s->rsa_kex_key = ssh_rsakex_newkey(rsakeydata.ptr, rsakeydata.len);
  1595. if (!s->rsa_kex_key) {
  1596. ssh_proto_error(s->ppl.ssh,
  1597. "Unable to parse RSA public key packet");
  1598. return;
  1599. }
  1600. put_stringpl(s->exhash, rsakeydata);
  1601. /*
  1602. * Next, set up a shared secret K, of precisely KLEN -
  1603. * 2*HLEN - 49 bits, where KLEN is the bit length of the
  1604. * RSA key modulus and HLEN is the bit length of the hash
  1605. * we're using.
  1606. */
  1607. {
  1608. int klen = ssh_rsakex_klen(s->rsa_kex_key);
  1609. int nbits = klen - (2*s->kex_alg->hash->hlen*8 + 49);
  1610. int i, byte = 0;
  1611. strbuf *buf;
  1612. unsigned char *outstr;
  1613. int outstrlen;
  1614. s->K = bn_power_2(nbits - 1);
  1615. for (i = 0; i < nbits; i++) {
  1616. if ((i & 7) == 0) {
  1617. byte = random_byte();
  1618. }
  1619. bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
  1620. }
  1621. /*
  1622. * Encode this as an mpint.
  1623. */
  1624. buf = strbuf_new();
  1625. put_mp_ssh2(buf, s->K);
  1626. /*
  1627. * Encrypt it with the given RSA key.
  1628. */
  1629. outstrlen = (klen + 7) / 8;
  1630. outstr = snewn(outstrlen, unsigned char);
  1631. ssh_rsakex_encrypt(s->kex_alg->hash, buf->u, buf->len,
  1632. outstr, outstrlen, s->rsa_kex_key);
  1633. /*
  1634. * And send it off in a return packet.
  1635. */
  1636. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_KEXRSA_SECRET);
  1637. put_string(pktout, outstr, outstrlen);
  1638. pq_push(s->ppl.out_pq, pktout);
  1639. put_string(s->exhash, outstr, outstrlen);
  1640. strbuf_free(buf);
  1641. sfree(outstr);
  1642. }
  1643. ssh_rsakex_freekey(s->rsa_kex_key);
  1644. s->rsa_kex_key = NULL;
  1645. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  1646. if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
  1647. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  1648. "expecting RSA kex signature, type %d (%s)",
  1649. pktin->type,
  1650. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1651. s->ppl.bpp->pls->actx,
  1652. pktin->type));
  1653. return;
  1654. }
  1655. s->sigdata = get_string(pktin);
  1656. if (get_err(pktin)) {
  1657. ssh_proto_error(s->ppl.ssh, "Unable to parse RSA kex signature");
  1658. return;
  1659. }
  1660. }
  1661. put_mp_ssh2(s->exhash, s->K);
  1662. assert(ssh_hash_alg(s->exhash)->hlen <= sizeof(s->exchange_hash));
  1663. ssh_hash_final(s->exhash, s->exchange_hash);
  1664. s->exhash = NULL;
  1665. #ifndef NO_GSSAPI
  1666. if (s->kex_alg->main_type == KEXTYPE_GSS) {
  1667. Ssh_gss_buf gss_buf;
  1668. SSH_GSS_CLEAR_BUF(&s->gss_buf);
  1669. gss_buf.value = s->exchange_hash;
  1670. gss_buf.length = s->kex_alg->hash->hlen;
  1671. s->gss_stat = s->shgss->lib->verify_mic(
  1672. s->shgss->lib, s->shgss->ctx, &gss_buf, &s->mic);
  1673. if (s->gss_stat != SSH_GSS_OK) {
  1674. if (s->shgss->lib->display_status(
  1675. s->shgss->lib, s->shgss->ctx, &s->gss_buf) == SSH_GSS_OK) {
  1676. char *err = s->gss_buf.value;
  1677. ssh_sw_abort(s->ppl.ssh, "GSSAPI key exchange MIC was "
  1678. "not valid: %s", err);
  1679. sfree(err);
  1680. } else {
  1681. ssh_sw_abort(s->ppl.ssh, "GSSAPI key exchange MIC was "
  1682. "not valid");
  1683. }
  1684. return;
  1685. }
  1686. s->gss_kex_used = TRUE;
  1687. /*-
  1688. * If this the first KEX, save the GSS context for "gssapi-keyex"
  1689. * authentication.
  1690. *
  1691. * http://tools.ietf.org/html/rfc4462#section-4
  1692. *
  1693. * This method may be used only if the initial key exchange was
  1694. * performed using a GSS-API-based key exchange method defined in
  1695. * accordance with Section 2. The GSS-API context used with this
  1696. * method is always that established during an initial GSS-API-based
  1697. * key exchange. Any context established during key exchange for the
  1698. * purpose of rekeying MUST NOT be used with this method.
  1699. */
  1700. if (s->got_session_id) {
  1701. s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
  1702. }
  1703. ppl_logevent(("GSSAPI Key Exchange complete!"));
  1704. }
  1705. #endif
  1706. s->dh_ctx = NULL;
  1707. #if 0
  1708. debug(("Exchange hash is:\n"));
  1709. dmemdump(s->exchange_hash, s->kex_alg->hash->hlen);
  1710. #endif
  1711. /* In GSS keyex there's no hostkey signature to verify */
  1712. if (s->kex_alg->main_type != KEXTYPE_GSS) {
  1713. if (!s->hkey) {
  1714. ssh_proto_error(s->ppl.ssh, "Server's host key is invalid");
  1715. return;
  1716. }
  1717. if (!ssh_key_verify(
  1718. s->hkey, s->sigdata,
  1719. make_ptrlen(s->exchange_hash, s->kex_alg->hash->hlen))) {
  1720. #ifndef FUZZING
  1721. ssh_proto_error(s->ppl.ssh, "Signature from server's host key "
  1722. "is invalid");
  1723. return;
  1724. #endif
  1725. }
  1726. }
  1727. s->keystr = (s->hkey ? ssh_key_cache_str(s->hkey) : NULL);
  1728. #ifndef NO_GSSAPI
  1729. if (s->gss_kex_used) {
  1730. /*
  1731. * In a GSS-based session, check the host key (if any) against
  1732. * the transient host key cache. See comment above, at the
  1733. * definition of ssh_transient_hostkey_cache_entry.
  1734. */
  1735. if (s->kex_alg->main_type == KEXTYPE_GSS) {
  1736. /*
  1737. * We've just done a GSS key exchange. If it gave us a
  1738. * host key, store it.
  1739. */
  1740. if (s->hkey) {
  1741. s->fingerprint = ssh2_fingerprint(s->hkey);
  1742. ppl_logevent(("GSS kex provided fallback host key:"));
  1743. ppl_logevent(("%s", s->fingerprint));
  1744. sfree(s->fingerprint);
  1745. s->fingerprint = NULL;
  1746. ssh_store_transient_hostkey(s, s->hkey);
  1747. } else if (!ssh_have_any_transient_hostkey(s)) {
  1748. /*
  1749. * But if it didn't, then we currently have no
  1750. * fallback host key to use in subsequent non-GSS
  1751. * rekeys. So we should immediately trigger a non-GSS
  1752. * rekey of our own, to set one up, before the session
  1753. * keys have been used for anything else.
  1754. *
  1755. * This is similar to the cross-certification done at
  1756. * user request in the permanent host key cache, but
  1757. * here we do it automatically, once, at session
  1758. * startup, and only add the key to the transient
  1759. * cache.
  1760. */
  1761. if (s->hostkey_alg) {
  1762. s->need_gss_transient_hostkey = TRUE;
  1763. } else {
  1764. /*
  1765. * If we negotiated the "null" host key algorithm
  1766. * in the key exchange, that's an indication that
  1767. * no host key at all is available from the server
  1768. * (both because we listed "null" last, and
  1769. * because RFC 4462 section 5 says that a server
  1770. * MUST NOT offer "null" as a host key algorithm
  1771. * unless that is the only algorithm it provides
  1772. * at all).
  1773. *
  1774. * In that case we actually _can't_ perform a
  1775. * non-GSSAPI key exchange, so it's pointless to
  1776. * attempt one proactively. This is also likely to
  1777. * cause trouble later if a rekey is required at a
  1778. * moment whne GSS credentials are not available,
  1779. * but someone setting up a server in this
  1780. * configuration presumably accepts that as a
  1781. * consequence.
  1782. */
  1783. if (!s->warned_about_no_gss_transient_hostkey) {
  1784. ppl_logevent(("No fallback host key available"));
  1785. s->warned_about_no_gss_transient_hostkey = TRUE;
  1786. }
  1787. }
  1788. }
  1789. } else {
  1790. /*
  1791. * We've just done a fallback key exchange, so make
  1792. * sure the host key it used is in the cache of keys
  1793. * we previously received in GSS kexes.
  1794. *
  1795. * An exception is if this was the non-GSS key exchange we
  1796. * triggered on purpose to populate the transient cache.
  1797. */
  1798. assert(s->hkey); /* only KEXTYPE_GSS lets this be null */
  1799. s->fingerprint = ssh2_fingerprint(s->hkey);
  1800. if (s->need_gss_transient_hostkey) {
  1801. ppl_logevent(("Post-GSS rekey provided fallback host key:"));
  1802. ppl_logevent(("%s", s->fingerprint));
  1803. ssh_store_transient_hostkey(s, s->hkey);
  1804. s->need_gss_transient_hostkey = FALSE;
  1805. } else if (!ssh_verify_transient_hostkey(s, s->hkey)) {
  1806. ppl_logevent(("Non-GSS rekey after initial GSS kex "
  1807. "used host key:"));
  1808. ppl_logevent(("%s", s->fingerprint));
  1809. ssh_sw_abort(s->ppl.ssh, "Server's host key did not match any "
  1810. "used in previous GSS kex");
  1811. return;
  1812. }
  1813. sfree(s->fingerprint);
  1814. s->fingerprint = NULL;
  1815. }
  1816. } else
  1817. #endif /* NO_GSSAPI */
  1818. if (!s->got_session_id) {
  1819. /*
  1820. * Make a note of any other host key formats that are available.
  1821. */
  1822. {
  1823. int i, j, nkeys = 0;
  1824. char *list = NULL;
  1825. for (i = 0; i < lenof(hostkey_algs); i++) {
  1826. if (hostkey_algs[i].alg == s->hostkey_alg)
  1827. continue;
  1828. for (j = 0; j < s->n_uncert_hostkeys; j++)
  1829. if (s->uncert_hostkeys[j] == i)
  1830. break;
  1831. if (j < s->n_uncert_hostkeys) {
  1832. char *newlist;
  1833. if (list)
  1834. newlist = dupprintf("%s/%s", list,
  1835. hostkey_algs[i].alg->ssh_id);
  1836. else
  1837. newlist = dupprintf("%s", hostkey_algs[i].alg->ssh_id);
  1838. sfree(list);
  1839. list = newlist;
  1840. nkeys++;
  1841. }
  1842. }
  1843. if (list) {
  1844. ppl_logevent(("Server also has %s host key%s, but we "
  1845. "don't know %s", list,
  1846. nkeys > 1 ? "s" : "",
  1847. nkeys > 1 ? "any of them" : "it"));
  1848. sfree(list);
  1849. }
  1850. }
  1851. /*
  1852. * Authenticate remote host: verify host key. (We've already
  1853. * checked the signature of the exchange hash.)
  1854. */
  1855. s->fingerprint = ssh2_fingerprint(s->hkey);
  1856. ppl_logevent(("Host key fingerprint is:"));
  1857. ppl_logevent(("%s", s->fingerprint));
  1858. /* First check against manually configured host keys. */
  1859. s->dlgret = verify_ssh_manual_host_key(
  1860. s->conf, s->fingerprint, s->hkey);
  1861. if (s->dlgret == 0) { /* did not match */
  1862. ssh_sw_abort(s->ppl.ssh, "Host key did not appear in manually "
  1863. "configured list");
  1864. return;
  1865. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  1866. s->dlgret = verify_ssh_host_key(s->ppl.frontend,
  1867. s->savedhost, s->savedport,
  1868. ssh_key_cache_id(s->hkey),
  1869. s->keystr, s->fingerprint,
  1870. ssh2_transport_dialog_callback, s);
  1871. #ifdef FUZZING
  1872. s->dlgret = 1;
  1873. #endif
  1874. crMaybeWaitUntilV(s->dlgret >= 0);
  1875. if (s->dlgret == 0) {
  1876. ssh_user_close(s->ppl.ssh,
  1877. "User aborted at host key verification");
  1878. return;
  1879. }
  1880. }
  1881. sfree(s->fingerprint);
  1882. s->fingerprint = NULL;
  1883. /*
  1884. * Save this host key, to check against the one presented in
  1885. * subsequent rekeys.
  1886. */
  1887. s->hostkey_str = s->keystr;
  1888. s->keystr = NULL;
  1889. } else if (s->cross_certifying) {
  1890. s->fingerprint = ssh2_fingerprint(s->hkey);
  1891. ppl_logevent(("Storing additional host key for this host:"));
  1892. ppl_logevent(("%s", s->fingerprint));
  1893. sfree(s->fingerprint);
  1894. s->fingerprint = NULL;
  1895. store_host_key(s->savedhost, s->savedport,
  1896. ssh_key_cache_id(s->hkey), s->keystr);
  1897. s->cross_certifying = FALSE;
  1898. /*
  1899. * Don't forget to store the new key as the one we'll be
  1900. * re-checking in future normal rekeys.
  1901. */
  1902. s->hostkey_str = s->keystr;
  1903. s->keystr = NULL;
  1904. } else {
  1905. /*
  1906. * In a rekey, we never present an interactive host key
  1907. * verification request to the user. Instead, we simply
  1908. * enforce that the key we're seeing this time is identical to
  1909. * the one we saw before.
  1910. */
  1911. if (strcmp(s->hostkey_str, s->keystr)) {
  1912. #ifndef FUZZING
  1913. ssh_sw_abort(s->ppl.ssh,
  1914. "Host key was different in repeat key exchange");
  1915. return;
  1916. #endif
  1917. }
  1918. }
  1919. sfree(s->keystr);
  1920. s->keystr = NULL;
  1921. if (s->hkey) {
  1922. ssh_key_free(s->hkey);
  1923. s->hkey = NULL;
  1924. }
  1925. /*
  1926. * The exchange hash from the very first key exchange is also
  1927. * the session id, used in session key construction and
  1928. * authentication.
  1929. */
  1930. if (!s->got_session_id) {
  1931. assert(sizeof(s->exchange_hash) <= sizeof(s->session_id));
  1932. memcpy(s->session_id, s->exchange_hash, sizeof(s->exchange_hash));
  1933. s->session_id_len = s->kex_alg->hash->hlen;
  1934. assert(s->session_id_len <= sizeof(s->session_id));
  1935. s->got_session_id = TRUE;
  1936. }
  1937. /*
  1938. * Send SSH2_MSG_NEWKEYS.
  1939. */
  1940. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_NEWKEYS);
  1941. pq_push(s->ppl.out_pq, pktout);
  1942. /* Start counting down the outgoing-data limit for these cipher keys. */
  1943. s->stats->out.running = TRUE;
  1944. s->stats->out.remaining = s->max_data_size;
  1945. /*
  1946. * Force the BPP to synchronously marshal all packets up to and
  1947. * including that NEWKEYS into wire format, before we switch over
  1948. * to new crypto.
  1949. */
  1950. ssh_bpp_handle_output(s->ppl.bpp);
  1951. /*
  1952. * We've sent client NEWKEYS, so create and initialise
  1953. * client-to-server session keys.
  1954. */
  1955. {
  1956. strbuf *cipher_key = strbuf_new();
  1957. strbuf *cipher_iv = strbuf_new();
  1958. strbuf *mac_key = strbuf_new();
  1959. if (s->out.cipher) {
  1960. ssh2_mkkey(s, cipher_iv, s->K, s->exchange_hash, 'A',
  1961. s->out.cipher->blksize);
  1962. ssh2_mkkey(s, cipher_key, s->K, s->exchange_hash, 'C',
  1963. s->out.cipher->padded_keybytes);
  1964. }
  1965. if (s->out.mac) {
  1966. ssh2_mkkey(s, mac_key, s->K, s->exchange_hash, 'E',
  1967. s->out.mac->keylen);
  1968. }
  1969. ssh2_bpp_new_outgoing_crypto(
  1970. s->ppl.bpp,
  1971. s->out.cipher, cipher_key->u, cipher_iv->u,
  1972. s->out.mac, s->out.etm_mode, mac_key->u,
  1973. s->out.comp);
  1974. strbuf_free(cipher_key);
  1975. strbuf_free(cipher_iv);
  1976. strbuf_free(mac_key);
  1977. }
  1978. if (s->out.cipher)
  1979. ppl_logevent(("Initialised %.200s client->server encryption",
  1980. s->out.cipher->text_name));
  1981. if (s->out.mac)
  1982. ppl_logevent(("Initialised %.200s client->server"
  1983. " MAC algorithm%s%s",
  1984. s->out.mac->text_name,
  1985. s->out.etm_mode ? " (in ETM mode)" : "",
  1986. (s->out.cipher->required_mac ?
  1987. " (required by cipher)" : "")));
  1988. if (s->out.comp->text_name)
  1989. ppl_logevent(("Initialised %s compression",
  1990. s->out.comp->text_name));
  1991. /*
  1992. * Now our end of the key exchange is complete, we can send all
  1993. * our queued higher-layer packets. Transfer the whole of the next
  1994. * layer's outgoing queue on to our own.
  1995. */
  1996. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  1997. /*
  1998. * Expect SSH2_MSG_NEWKEYS from server.
  1999. */
  2000. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  2001. if (pktin->type != SSH2_MSG_NEWKEYS) {
  2002. ssh_proto_error(s->ppl.ssh, "Received unexpected packet when "
  2003. "expecting SSH_MSG_NEWKEYS, type %d (%s)",
  2004. pktin->type,
  2005. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  2006. s->ppl.bpp->pls->actx,
  2007. pktin->type));
  2008. return;
  2009. }
  2010. /* Start counting down the incoming-data limit for these cipher keys. */
  2011. s->stats->in.running = TRUE;
  2012. s->stats->in.remaining = s->max_data_size;
  2013. /*
  2014. * We've seen server NEWKEYS, so create and initialise
  2015. * server-to-client session keys.
  2016. */
  2017. {
  2018. strbuf *cipher_key = strbuf_new();
  2019. strbuf *cipher_iv = strbuf_new();
  2020. strbuf *mac_key = strbuf_new();
  2021. if (s->in.cipher) {
  2022. ssh2_mkkey(s, cipher_iv, s->K, s->exchange_hash, 'B',
  2023. s->in.cipher->blksize);
  2024. ssh2_mkkey(s, cipher_key, s->K, s->exchange_hash, 'D',
  2025. s->in.cipher->padded_keybytes);
  2026. }
  2027. if (s->in.mac) {
  2028. ssh2_mkkey(s, mac_key, s->K, s->exchange_hash, 'F',
  2029. s->in.mac->keylen);
  2030. }
  2031. ssh2_bpp_new_incoming_crypto(
  2032. s->ppl.bpp,
  2033. s->in.cipher, cipher_key->u, cipher_iv->u,
  2034. s->in.mac, s->in.etm_mode, mac_key->u,
  2035. s->in.comp);
  2036. strbuf_free(cipher_key);
  2037. strbuf_free(cipher_iv);
  2038. strbuf_free(mac_key);
  2039. }
  2040. if (s->in.cipher)
  2041. ppl_logevent(("Initialised %.200s server->client encryption",
  2042. s->in.cipher->text_name));
  2043. if (s->in.mac)
  2044. ppl_logevent(("Initialised %.200s server->client MAC algorithm%s%s",
  2045. s->in.mac->text_name,
  2046. s->in.etm_mode ? " (in ETM mode)" : "",
  2047. (s->in.cipher->required_mac ?
  2048. " (required by cipher)" : "")));
  2049. if (s->in.comp->text_name)
  2050. ppl_logevent(("Initialised %s decompression",
  2051. s->in.comp->text_name));
  2052. /*
  2053. * Free shared secret.
  2054. */
  2055. freebn(s->K); s->K = NULL;
  2056. /*
  2057. * Update the specials menu to list the remaining uncertified host
  2058. * keys.
  2059. */
  2060. update_specials_menu(s->ppl.frontend);
  2061. /*
  2062. * Key exchange is over. Loop straight back round if we have a
  2063. * deferred rekey reason.
  2064. */
  2065. if (s->deferred_rekey_reason) {
  2066. ppl_logevent(("%s", s->deferred_rekey_reason));
  2067. pktin = NULL;
  2068. s->deferred_rekey_reason = NULL;
  2069. goto begin_key_exchange;
  2070. }
  2071. /*
  2072. * Otherwise, schedule a timer for our next rekey.
  2073. */
  2074. s->kex_in_progress = FALSE;
  2075. s->last_rekey = GETTICKCOUNT();
  2076. (void) ssh2_transport_timer_update(s, 0);
  2077. /*
  2078. * Now we're encrypting. Get the next-layer protocol started if it
  2079. * hasn't already, and then sit here waiting for reasons to go
  2080. * back to the start and do a repeat key exchange. One of those
  2081. * reasons is that we receive KEXINIT from the other end; the
  2082. * other is if we find rekey_reason is non-NULL, i.e. we've
  2083. * decided to initiate a rekey ourselves for some reason.
  2084. */
  2085. if (!s->higher_layer_ok) {
  2086. pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_SERVICE_REQUEST);
  2087. put_stringz(pktout, s->higher_layer->vt->name);
  2088. pq_push(s->ppl.out_pq, pktout);
  2089. crMaybeWaitUntilV((pktin = ssh2_transport_pop(s)) != NULL);
  2090. if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
  2091. ssh_sw_abort(s->ppl.ssh, "Server refused request to start "
  2092. "'%s' protocol", s->higher_layer->vt->name);
  2093. return;
  2094. }
  2095. s->higher_layer_ok = TRUE;
  2096. queue_idempotent_callback(&s->higher_layer->ic_process_queue);
  2097. }
  2098. s->rekey_class = RK_NONE;
  2099. do {
  2100. crReturnV;
  2101. /* Pass through outgoing packets from the higher layer. */
  2102. pq_concatenate(s->ppl.out_pq, s->ppl.out_pq, &s->pq_out_higher);
  2103. /* Wait for either a KEXINIT, or something setting
  2104. * s->rekey_class. This call to ssh2_transport_pop also has
  2105. * the side effect of transferring incoming packets _to_ the
  2106. * higher layer (via filter_queue). */
  2107. if ((pktin = ssh2_transport_pop(s)) != NULL) {
  2108. if (pktin->type != SSH2_MSG_KEXINIT) {
  2109. ssh_proto_error(s->ppl.ssh, "Received unexpected transport-"
  2110. "layer packet outside a key exchange, "
  2111. "type %d (%s)", pktin->type,
  2112. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  2113. s->ppl.bpp->pls->actx,
  2114. pktin->type));
  2115. return;
  2116. }
  2117. pq_push_front(s->ppl.in_pq, pktin);
  2118. ppl_logevent(("Server initiated key re-exchange"));
  2119. s->rekey_class = RK_SERVER;
  2120. }
  2121. if (s->rekey_class == RK_POST_USERAUTH) {
  2122. /*
  2123. * userauth has seen a USERAUTH_SUCCEEDED. For a couple of
  2124. * reasons, this may be the moment to do an immediate
  2125. * rekey with different parameters. But it may not; so
  2126. * here we turn that rekey class into either RK_NONE or
  2127. * RK_NORMAL.
  2128. *
  2129. * One is to turn on delayed compression. We do this by a
  2130. * rekey to work around a protocol design bug:
  2131. * draft-miller-secsh-compression-delayed-00 says that you
  2132. * negotiate delayed compression in the first key
  2133. * exchange, and both sides start compressing when the
  2134. * server has sent USERAUTH_SUCCESS. This has a race
  2135. * condition -- the server can't know when the client has
  2136. * seen it, and thus which incoming packets it should
  2137. * treat as compressed.
  2138. *
  2139. * Instead, we do the initial key exchange without
  2140. * offering the delayed methods, but note if the server
  2141. * offers them; when we get here, if a delayed method was
  2142. * available that was higher on our list than what we got,
  2143. * we initiate a rekey in which we _do_ list the delayed
  2144. * methods (and hopefully get it as a result). Subsequent
  2145. * rekeys will do the same.
  2146. *
  2147. * Another reason for a rekey at this point is if we've
  2148. * done a GSS key exchange and don't have anything in our
  2149. * transient hostkey cache, in which case we should make
  2150. * an attempt to populate the cache now.
  2151. */
  2152. assert(!s->userauth_succeeded); /* should only happen once */
  2153. s->userauth_succeeded = TRUE;
  2154. if (s->pending_compression) {
  2155. s->rekey_reason = "enabling delayed compression";
  2156. s->rekey_class = RK_NORMAL;
  2157. } else if (s->need_gss_transient_hostkey) {
  2158. s->rekey_reason = "populating transient host key cache";
  2159. s->rekey_class = RK_NORMAL;
  2160. } else {
  2161. /* No need to rekey at this time. */
  2162. s->rekey_class = RK_NONE;
  2163. }
  2164. }
  2165. if (!s->rekey_class) {
  2166. /* If we don't yet have any other reason to rekey, check
  2167. * if we've hit our data limit in either direction. */
  2168. if (!s->stats->in.running) {
  2169. s->rekey_reason = "too much data received";
  2170. s->rekey_class = RK_NORMAL;
  2171. } else if (!s->stats->out.running) {
  2172. s->rekey_reason = "too much data sent";
  2173. s->rekey_class = RK_NORMAL;
  2174. }
  2175. }
  2176. if (s->rekey_class != RK_NONE && s->rekey_class != RK_SERVER) {
  2177. /*
  2178. * Special case: if the server bug is set that doesn't
  2179. * allow rekeying, we give a different log message and
  2180. * continue waiting. (If such a server _initiates_ a
  2181. * rekey, we process it anyway!)
  2182. */
  2183. if ((s->ppl.remote_bugs & BUG_SSH2_REKEY)) {
  2184. ppl_logevent(("Server bug prevents key re-exchange (%s)",
  2185. s->rekey_reason));
  2186. /* Reset the counters, so that at least this message doesn't
  2187. * hit the event log _too_ often. */
  2188. s->stats->in.running = s->stats->out.running = TRUE;
  2189. s->stats->in.remaining = s->stats->out.remaining =
  2190. s->max_data_size;
  2191. (void) ssh2_transport_timer_update(s, 0);
  2192. s->rekey_class = RK_NONE;
  2193. } else {
  2194. ppl_logevent(("Initiating key re-exchange (%s)",
  2195. s->rekey_reason));
  2196. }
  2197. }
  2198. } while (s->rekey_reason == RK_NONE);
  2199. /* Once we exit the above loop, we really are rekeying. */
  2200. goto begin_key_exchange;
  2201. crFinishV;
  2202. }
  2203. static void ssh2_transport_higher_layer_packet_callback(void *context)
  2204. {
  2205. PacketProtocolLayer *ppl = (PacketProtocolLayer *)context;
  2206. ssh_ppl_process_queue(ppl);
  2207. }
  2208. static void ssh2_transport_timer(void *ctx, unsigned long now)
  2209. {
  2210. struct ssh2_transport_state *s = (struct ssh2_transport_state *)ctx;
  2211. unsigned long mins;
  2212. unsigned long ticks;
  2213. // WINSCP: our WINSCP_QUERY_TIMER implementation of schedule_timer
  2214. // does not guarantee the `now` to be exactly as scheduled
  2215. if (s->kex_in_progress || now < s->next_rekey)
  2216. return;
  2217. mins = sanitise_rekey_time(conf_get_int(s->conf, CONF_ssh_rekey_time), 60);
  2218. if (mins == 0)
  2219. return;
  2220. /* Rekey if enough time has elapsed */
  2221. ticks = mins * 60 * TICKSPERSEC;
  2222. if (now - s->last_rekey > ticks - 30*TICKSPERSEC) {
  2223. s->rekey_reason = "timeout";
  2224. s->rekey_class = RK_NORMAL;
  2225. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2226. return;
  2227. }
  2228. #ifndef NO_GSSAPI
  2229. /*
  2230. * Rekey now if we have a new cred or context expires this cycle,
  2231. * but not if this is unsafe.
  2232. */
  2233. if (conf_get_int(s->conf, CONF_gssapirekey)) {
  2234. ssh2_transport_gss_update(s, FALSE);
  2235. if ((s->gss_status & GSS_KEX_CAPABLE) != 0 &&
  2236. (s->gss_status & GSS_CTXT_MAYFAIL) == 0 &&
  2237. (s->gss_status & (GSS_CRED_UPDATED|GSS_CTXT_EXPIRES)) != 0) {
  2238. s->rekey_reason = "GSS credentials updated";
  2239. s->rekey_class = RK_GSS_UPDATE;
  2240. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2241. return;
  2242. }
  2243. }
  2244. #endif
  2245. /* Try again later. */
  2246. (void) ssh2_transport_timer_update(s, 0);
  2247. }
  2248. /*
  2249. * The rekey_time is zero except when re-configuring.
  2250. *
  2251. * We either schedule the next timer and return 0, or return 1 to run the
  2252. * callback now, which will call us again to re-schedule on completion.
  2253. */
  2254. static int ssh2_transport_timer_update(struct ssh2_transport_state *s,
  2255. unsigned long rekey_time)
  2256. {
  2257. unsigned long mins;
  2258. unsigned long ticks;
  2259. mins = sanitise_rekey_time(conf_get_int(s->conf, CONF_ssh_rekey_time), 60);
  2260. ticks = mins * 60 * TICKSPERSEC;
  2261. /* Handle change from previous setting */
  2262. if (rekey_time != 0 && rekey_time != mins) {
  2263. unsigned long next;
  2264. unsigned long now = GETTICKCOUNT();
  2265. mins = rekey_time;
  2266. ticks = mins * 60 * TICKSPERSEC;
  2267. next = s->last_rekey + ticks;
  2268. /* If overdue, caller will rekey synchronously now */
  2269. if (now - s->last_rekey > ticks)
  2270. return 1;
  2271. ticks = next - now;
  2272. }
  2273. #ifndef NO_GSSAPI
  2274. if (s->gss_kex_used) {
  2275. /*
  2276. * If we've used GSSAPI key exchange, then we should
  2277. * periodically check whether we need to do another one to
  2278. * pass new credentials to the server.
  2279. */
  2280. unsigned long gssmins;
  2281. /* Check cascade conditions more frequently if configured */
  2282. gssmins = sanitise_rekey_time(
  2283. conf_get_int(s->conf, CONF_gssapirekey), GSS_DEF_REKEY_MINS);
  2284. if (gssmins > 0) {
  2285. if (gssmins < mins)
  2286. ticks = (mins = gssmins) * 60 * TICKSPERSEC;
  2287. if ((s->gss_status & GSS_KEX_CAPABLE) != 0) {
  2288. /*
  2289. * Run next timer even sooner if it would otherwise be
  2290. * too close to the context expiration time
  2291. */
  2292. if ((s->gss_status & GSS_CTXT_EXPIRES) == 0 &&
  2293. s->gss_ctxt_lifetime - mins * 60 < 2 * MIN_CTXT_LIFETIME)
  2294. ticks -= 2 * MIN_CTXT_LIFETIME * TICKSPERSEC;
  2295. }
  2296. }
  2297. }
  2298. #endif
  2299. /* Schedule the next timer */
  2300. s->next_rekey = schedule_timer(ticks, ssh2_transport_timer, s);
  2301. return 0;
  2302. }
  2303. static void ssh2_transport_dialog_callback(void *loginv, int ret)
  2304. {
  2305. struct ssh2_transport_state *s = (struct ssh2_transport_state *)loginv;
  2306. s->dlgret = ret;
  2307. ssh_ppl_process_queue(&s->ppl);
  2308. }
  2309. #ifndef NO_GSSAPI
  2310. /*
  2311. * This is called at the beginning of each SSH rekey to determine
  2312. * whether we are GSS capable, and if we did GSS key exchange, and are
  2313. * delegating credentials, it is also called periodically to determine
  2314. * whether we should rekey in order to delegate (more) fresh
  2315. * credentials. This is called "credential cascading".
  2316. *
  2317. * On Windows, with SSPI, we may not get the credential expiration, as
  2318. * Windows automatically renews from cached passwords, so the
  2319. * credential effectively never expires. Since we still want to
  2320. * cascade when the local TGT is updated, we use the expiration of a
  2321. * newly obtained context as a proxy for the expiration of the TGT.
  2322. */
  2323. static void ssh2_transport_gss_update(struct ssh2_transport_state *s,
  2324. int definitely_rekeying)
  2325. {
  2326. PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
  2327. int gss_stat;
  2328. time_t gss_cred_expiry;
  2329. unsigned long mins;
  2330. Ssh_gss_buf gss_sndtok;
  2331. Ssh_gss_buf gss_rcvtok;
  2332. Ssh_gss_ctx gss_ctx;
  2333. s->gss_status = 0;
  2334. /*
  2335. * Nothing to do if no GSSAPI libraries are configured or GSSAPI
  2336. * auth is not enabled.
  2337. */
  2338. if (s->shgss->libs->nlibraries == 0)
  2339. return;
  2340. if (!conf_get_int(s->conf, CONF_try_gssapi_auth) &&
  2341. !conf_get_int(s->conf, CONF_try_gssapi_kex))
  2342. return;
  2343. /* Import server name and cache it */
  2344. if (s->shgss->srv_name == GSS_C_NO_NAME) {
  2345. gss_stat = s->shgss->lib->import_name(
  2346. s->shgss->lib, s->fullhostname, &s->shgss->srv_name);
  2347. if (gss_stat != SSH_GSS_OK) {
  2348. if (gss_stat == SSH_GSS_BAD_HOST_NAME)
  2349. ppl_logevent(("GSSAPI import name failed - Bad service name;"
  2350. " won't use GSS key exchange"));
  2351. else
  2352. ppl_logevent(("GSSAPI import name failed;"
  2353. " won't use GSS key exchange"));
  2354. return;
  2355. }
  2356. }
  2357. /*
  2358. * Do we (still) have credentials? Capture the credential
  2359. * expiration when available
  2360. */
  2361. gss_stat = s->shgss->lib->acquire_cred(
  2362. s->shgss->lib, &gss_ctx, &gss_cred_expiry);
  2363. if (gss_stat != SSH_GSS_OK)
  2364. return;
  2365. SSH_GSS_CLEAR_BUF(&gss_sndtok);
  2366. SSH_GSS_CLEAR_BUF(&gss_rcvtok);
  2367. /*
  2368. * When acquire_cred yields no useful expiration, get a proxy for
  2369. * the cred expiration from the context expiration.
  2370. */
  2371. gss_stat = s->shgss->lib->init_sec_context(
  2372. s->shgss->lib, &gss_ctx, s->shgss->srv_name,
  2373. 0 /* don't delegate */, &gss_rcvtok, &gss_sndtok,
  2374. (gss_cred_expiry == GSS_NO_EXPIRATION ? &gss_cred_expiry : NULL),
  2375. &s->gss_ctxt_lifetime);
  2376. /* This context was for testing only. */
  2377. if (gss_ctx)
  2378. s->shgss->lib->release_cred(s->shgss->lib, &gss_ctx);
  2379. if (gss_stat != SSH_GSS_OK &&
  2380. gss_stat != SSH_GSS_S_CONTINUE_NEEDED) {
  2381. /*
  2382. * No point in verbosely interrupting the user to tell them we
  2383. * couldn't get GSS credentials, if this was only a check
  2384. * between key exchanges to see if fresh ones were available.
  2385. * When we do do a rekey, this message (if displayed) will
  2386. * appear among the standard rekey blurb, but when we're not,
  2387. * it shouldn't pop up all the time regardless.
  2388. */
  2389. if (definitely_rekeying)
  2390. ppl_logevent(("No GSSAPI security context available"));
  2391. return;
  2392. }
  2393. if (gss_sndtok.length)
  2394. s->shgss->lib->free_tok(s->shgss->lib, &gss_sndtok);
  2395. s->gss_status |= GSS_KEX_CAPABLE;
  2396. /*
  2397. * When rekeying to cascade, avoding doing this too close to the
  2398. * context expiration time, since the key exchange might fail.
  2399. */
  2400. if (s->gss_ctxt_lifetime < MIN_CTXT_LIFETIME)
  2401. s->gss_status |= GSS_CTXT_MAYFAIL;
  2402. /*
  2403. * If we're not delegating credentials, rekeying is not used to
  2404. * refresh them. We must avoid setting GSS_CRED_UPDATED or
  2405. * GSS_CTXT_EXPIRES when credential delegation is disabled.
  2406. */
  2407. if (conf_get_int(s->conf, CONF_gssapifwd) == 0)
  2408. return;
  2409. if (s->gss_cred_expiry != GSS_NO_EXPIRATION &&
  2410. difftime(gss_cred_expiry, s->gss_cred_expiry) > 0)
  2411. s->gss_status |= GSS_CRED_UPDATED;
  2412. mins = sanitise_rekey_time(
  2413. conf_get_int(s->conf, CONF_gssapirekey), GSS_DEF_REKEY_MINS);
  2414. if (mins > 0 && s->gss_ctxt_lifetime <= mins * 60)
  2415. s->gss_status |= GSS_CTXT_EXPIRES;
  2416. }
  2417. /*
  2418. * Data structure managing host keys in sessions based on GSSAPI KEX.
  2419. *
  2420. * In a session we started with a GSSAPI key exchange, the concept of
  2421. * 'host key' has completely different lifetime and security semantics
  2422. * from the usual ones. Per RFC 4462 section 2.1, we assume that any
  2423. * host key delivered to us in the course of a GSSAPI key exchange is
  2424. * _solely_ there to use as a transient fallback within the same
  2425. * session, if at the time of a subsequent rekey the GSS credentials
  2426. * are temporarily invalid and so a non-GSS KEX method has to be used.
  2427. *
  2428. * In particular, in a GSS-based SSH deployment, host keys may not
  2429. * even _be_ persistent identities for the server; it would be
  2430. * legitimate for a server to generate a fresh one routinely if it
  2431. * wanted to, like SSH-1 server keys.
  2432. *
  2433. * So, in this mode, we never touch the persistent host key cache at
  2434. * all, either to check keys against it _or_ to store keys in it.
  2435. * Instead, we maintain an in-memory cache of host keys that have been
  2436. * mentioned in GSS key exchanges within this particular session, and
  2437. * we permit precisely those host keys in non-GSS rekeys.
  2438. */
  2439. struct ssh_transient_hostkey_cache_entry {
  2440. const ssh_keyalg *alg;
  2441. strbuf *pub_blob;
  2442. };
  2443. static int ssh_transient_hostkey_cache_cmp(void *av, void *bv)
  2444. {
  2445. const struct ssh_transient_hostkey_cache_entry
  2446. *a = (const struct ssh_transient_hostkey_cache_entry *)av,
  2447. *b = (const struct ssh_transient_hostkey_cache_entry *)bv;
  2448. return strcmp(a->alg->ssh_id, b->alg->ssh_id);
  2449. }
  2450. static int ssh_transient_hostkey_cache_find(void *av, void *bv)
  2451. {
  2452. const ssh_keyalg *aalg = (const ssh_keyalg *)av;
  2453. const struct ssh_transient_hostkey_cache_entry
  2454. *b = (const struct ssh_transient_hostkey_cache_entry *)bv;
  2455. return strcmp(aalg->ssh_id, b->alg->ssh_id);
  2456. }
  2457. static void ssh_init_transient_hostkey_store(
  2458. struct ssh2_transport_state *s)
  2459. {
  2460. s->transient_hostkey_cache =
  2461. newtree234(ssh_transient_hostkey_cache_cmp);
  2462. }
  2463. static void ssh_cleanup_transient_hostkey_store(
  2464. struct ssh2_transport_state *s)
  2465. {
  2466. struct ssh_transient_hostkey_cache_entry *ent;
  2467. while ((ent = delpos234(s->transient_hostkey_cache, 0)) != NULL) {
  2468. strbuf_free(ent->pub_blob);
  2469. sfree(ent);
  2470. }
  2471. freetree234(s->transient_hostkey_cache);
  2472. }
  2473. static void ssh_store_transient_hostkey(
  2474. struct ssh2_transport_state *s, ssh_key *key)
  2475. {
  2476. struct ssh_transient_hostkey_cache_entry *ent, *retd;
  2477. if ((ent = find234(s->transient_hostkey_cache, (void *)ssh_key_alg(key),
  2478. ssh_transient_hostkey_cache_find)) != NULL) {
  2479. strbuf_free(ent->pub_blob);
  2480. sfree(ent);
  2481. }
  2482. ent = snew(struct ssh_transient_hostkey_cache_entry);
  2483. ent->alg = ssh_key_alg(key);
  2484. ent->pub_blob = strbuf_new();
  2485. ssh_key_public_blob(key, BinarySink_UPCAST(ent->pub_blob));
  2486. retd = add234(s->transient_hostkey_cache, ent);
  2487. assert(retd == ent);
  2488. }
  2489. static int ssh_verify_transient_hostkey(
  2490. struct ssh2_transport_state *s, ssh_key *key)
  2491. {
  2492. struct ssh_transient_hostkey_cache_entry *ent;
  2493. int toret = FALSE;
  2494. if ((ent = find234(s->transient_hostkey_cache, (void *)ssh_key_alg(key),
  2495. ssh_transient_hostkey_cache_find)) != NULL) {
  2496. strbuf *this_blob = strbuf_new();
  2497. ssh_key_public_blob(key, BinarySink_UPCAST(this_blob));
  2498. if (this_blob->len == ent->pub_blob->len &&
  2499. !memcmp(this_blob->s, ent->pub_blob->s,
  2500. this_blob->len))
  2501. toret = TRUE;
  2502. strbuf_free(this_blob);
  2503. }
  2504. return toret;
  2505. }
  2506. static int ssh_have_transient_hostkey(
  2507. struct ssh2_transport_state *s, const ssh_keyalg *alg)
  2508. {
  2509. struct ssh_transient_hostkey_cache_entry *ent =
  2510. find234(s->transient_hostkey_cache, (void *)alg,
  2511. ssh_transient_hostkey_cache_find);
  2512. return ent != NULL;
  2513. }
  2514. static int ssh_have_any_transient_hostkey(
  2515. struct ssh2_transport_state *s)
  2516. {
  2517. return count234(s->transient_hostkey_cache) > 0;
  2518. }
  2519. ptrlen ssh2_transport_get_session_id(PacketProtocolLayer *ppl)
  2520. {
  2521. struct ssh2_transport_state *s;
  2522. assert(ppl->vt == &ssh2_transport_vtable);
  2523. s = FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2524. assert(s->got_session_id);
  2525. return make_ptrlen(s->session_id, s->session_id_len);
  2526. }
  2527. void ssh2_transport_notify_auth_done(PacketProtocolLayer *ppl)
  2528. {
  2529. struct ssh2_transport_state *s;
  2530. assert(ppl->vt == &ssh2_transport_vtable);
  2531. s = FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2532. s->rekey_reason = NULL; /* will be filled in later */
  2533. s->rekey_class = RK_POST_USERAUTH;
  2534. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2535. }
  2536. #endif /* NO_GSSAPI */
  2537. static int ssh2_transport_get_specials(
  2538. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
  2539. {
  2540. struct ssh2_transport_state *s =
  2541. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2542. int need_separator = FALSE;
  2543. int toret;
  2544. if (ssh_ppl_get_specials(s->higher_layer, add_special, ctx)) {
  2545. need_separator = TRUE;
  2546. toret = TRUE;
  2547. }
  2548. /*
  2549. * Don't bother offering rekey-based specials if we've decided the
  2550. * remote won't cope with it, since we wouldn't bother sending it
  2551. * if asked anyway.
  2552. */
  2553. if (!(s->ppl.remote_bugs & BUG_SSH2_REKEY)) {
  2554. if (need_separator) {
  2555. add_special(ctx, NULL, SS_SEP, 0);
  2556. need_separator = FALSE;
  2557. }
  2558. add_special(ctx, "Repeat key exchange", SS_REKEY, 0);
  2559. toret = TRUE;
  2560. if (s->n_uncert_hostkeys) {
  2561. int i;
  2562. add_special(ctx, NULL, SS_SEP, 0);
  2563. add_special(ctx, "Cache new host key type", SS_SUBMENU, 0);
  2564. for (i = 0; i < s->n_uncert_hostkeys; i++) {
  2565. const ssh_keyalg *alg =
  2566. hostkey_algs[s->uncert_hostkeys[i]].alg;
  2567. add_special(ctx, alg->ssh_id, SS_XCERT, s->uncert_hostkeys[i]);
  2568. }
  2569. add_special(ctx, NULL, SS_EXITMENU, 0);
  2570. }
  2571. }
  2572. return toret;
  2573. }
  2574. static void ssh2_transport_special_cmd(PacketProtocolLayer *ppl,
  2575. SessionSpecialCode code, int arg)
  2576. {
  2577. struct ssh2_transport_state *s =
  2578. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2579. if (code == SS_REKEY) {
  2580. if (!s->kex_in_progress) {
  2581. s->rekey_reason = "at user request";
  2582. s->rekey_class = RK_NORMAL;
  2583. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2584. }
  2585. } else if (code == SS_XCERT) {
  2586. if (!s->kex_in_progress) {
  2587. s->hostkey_alg = hostkey_algs[arg].alg;
  2588. s->cross_certifying = TRUE;
  2589. s->rekey_reason = "cross-certifying new host key";
  2590. s->rekey_class = RK_NORMAL;
  2591. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2592. }
  2593. } else {
  2594. /* Send everything else to the next layer up. This includes
  2595. * SS_PING/SS_NOP, which we _could_ handle here - but it's
  2596. * better to put them in the connection layer, so they'll
  2597. * still work in bare connection mode. */
  2598. ssh_ppl_special_cmd(s->higher_layer, code, arg);
  2599. }
  2600. }
  2601. /* Safely convert rekey_time to unsigned long minutes */
  2602. static unsigned long sanitise_rekey_time(int rekey_time, unsigned long def)
  2603. {
  2604. if (rekey_time < 0 || rekey_time > MAX_TICK_MINS)
  2605. rekey_time = def;
  2606. return (unsigned long)rekey_time;
  2607. }
  2608. static void ssh2_transport_set_max_data_size(struct ssh2_transport_state *s)
  2609. {
  2610. s->max_data_size = parse_blocksize(
  2611. conf_get_str(s->conf, CONF_ssh_rekey_data));
  2612. }
  2613. static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf)
  2614. {
  2615. struct ssh2_transport_state *s;
  2616. const char *rekey_reason = NULL;
  2617. int rekey_mandatory = FALSE;
  2618. unsigned long old_max_data_size, rekey_time;
  2619. int i;
  2620. assert(ppl->vt == &ssh2_transport_vtable);
  2621. s = FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2622. rekey_time = sanitise_rekey_time(
  2623. conf_get_int(conf, CONF_ssh_rekey_time), 60);
  2624. if (ssh2_transport_timer_update(s, rekey_time))
  2625. rekey_reason = "timeout shortened";
  2626. old_max_data_size = s->max_data_size;
  2627. ssh2_transport_set_max_data_size(s);
  2628. if (old_max_data_size != s->max_data_size &&
  2629. s->max_data_size != 0) {
  2630. if (s->max_data_size < old_max_data_size) {
  2631. unsigned long diff = old_max_data_size - s->max_data_size;
  2632. /* Intentionally use bitwise OR instead of logical, so
  2633. * that we decrement both counters even if the first one
  2634. * runs out */
  2635. if ((DTS_CONSUME(s->stats, out, diff) != 0) |
  2636. (DTS_CONSUME(s->stats, in, diff) != 0))
  2637. rekey_reason = "data limit lowered";
  2638. } else {
  2639. unsigned long diff = s->max_data_size - old_max_data_size;
  2640. if (s->stats->out.running)
  2641. s->stats->out.remaining += diff;
  2642. if (s->stats->in.running)
  2643. s->stats->in.remaining += diff;
  2644. }
  2645. }
  2646. if (conf_get_int(s->conf, CONF_compression) !=
  2647. conf_get_int(conf, CONF_compression)) {
  2648. rekey_reason = "compression setting changed";
  2649. rekey_mandatory = TRUE;
  2650. }
  2651. for (i = 0; i < CIPHER_MAX; i++)
  2652. if (conf_get_int_int(s->conf, CONF_ssh_cipherlist, i) !=
  2653. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  2654. rekey_reason = "cipher settings changed";
  2655. rekey_mandatory = TRUE;
  2656. }
  2657. if (conf_get_int(s->conf, CONF_ssh2_des_cbc) !=
  2658. conf_get_int(conf, CONF_ssh2_des_cbc)) {
  2659. rekey_reason = "cipher settings changed";
  2660. rekey_mandatory = TRUE;
  2661. }
  2662. conf_free(s->conf);
  2663. s->conf = conf_copy(conf);
  2664. if (rekey_reason) {
  2665. if (!s->kex_in_progress) {
  2666. s->rekey_reason = rekey_reason;
  2667. s->rekey_class = RK_NORMAL;
  2668. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2669. } else if (rekey_mandatory) {
  2670. s->deferred_rekey_reason = rekey_reason;
  2671. }
  2672. }
  2673. /* Also pass the configuration along to our higher layer */
  2674. ssh_ppl_reconfigure(s->higher_layer, conf);
  2675. }
  2676. static int ssh2_transport_want_user_input(PacketProtocolLayer *ppl)
  2677. {
  2678. struct ssh2_transport_state *s =
  2679. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2680. /* Just delegate this to the higher layer */
  2681. return ssh_ppl_want_user_input(s->higher_layer);
  2682. }
  2683. static void ssh2_transport_got_user_input(PacketProtocolLayer *ppl)
  2684. {
  2685. struct ssh2_transport_state *s =
  2686. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2687. /* Just delegate this to the higher layer */
  2688. ssh_ppl_got_user_input(s->higher_layer);
  2689. }
  2690. #include "puttyexp.h"
  2691. static unsigned int ssh2_transport_winscp_query(PacketProtocolLayer *ppl, int query)
  2692. {
  2693. struct ssh2_transport_state *s =
  2694. FROMFIELD(ppl, struct ssh2_transport_state, ppl);
  2695. if (query == WINSCP_QUERY_TIMER)
  2696. {
  2697. ssh2_transport_timer(s, GETTICKCOUNT());
  2698. return 1;
  2699. }
  2700. else if (s->higher_layer->vt->winscp_query != NULL)
  2701. {
  2702. return ssh_ppl_winscp_query(s->higher_layer, query);
  2703. }
  2704. else
  2705. {
  2706. return 0;
  2707. }
  2708. }
  2709. // WINSCP
  2710. void get_hostkey_algs(int * count, cp_ssh_keyalg * SignKeys)
  2711. {
  2712. int i;
  2713. assert(lenof(hostkey_algs) <= *count);
  2714. *count = lenof(hostkey_algs);
  2715. for (i = 0; i < *count; i++)
  2716. {
  2717. *(SignKeys + i) = hostkey_algs[i].alg;
  2718. }
  2719. }
  2720. // WINSCP
  2721. void get_macs(int * count, const struct ssh2_macalg *** amacs)
  2722. {
  2723. *amacs = macs;
  2724. *count = lenof(macs);
  2725. }
  2726. void call_ssh_timer(Backend * be)
  2727. {
  2728. // TODO
  2729. }