ssh2transport.c 112 KB

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