userauth2-client.c 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616
  1. /*
  2. * Packet protocol layer for the client side of the SSH-2 userauth
  3. * protocol (RFC 4252).
  4. */
  5. #include <assert.h>
  6. #include "putty.h"
  7. #include "ssh.h"
  8. #include "bpp.h"
  9. #include "ppl.h"
  10. #include "sshcr.h"
  11. #ifndef NO_GSSAPI
  12. #include "gssc.h"
  13. #include "gss.h"
  14. #endif
  15. #define BANNER_LIMIT 131072
  16. typedef struct agent_key {
  17. strbuf *blob, *comment;
  18. ptrlen algorithm;
  19. } agent_key;
  20. struct ssh2_userauth_state {
  21. int crState;
  22. PacketProtocolLayer *transport_layer, *successor_layer;
  23. Filename *keyfile, *detached_cert_file;
  24. bool show_banner, tryagent, notrivialauth, change_username;
  25. char *hostname, *fullhostname;
  26. int port;
  27. char *default_username;
  28. bool try_ki_auth, try_gssapi_auth, try_gssapi_kex_auth, gssapi_fwd;
  29. ptrlen session_id;
  30. enum {
  31. AUTH_TYPE_NONE,
  32. AUTH_TYPE_PUBLICKEY,
  33. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  34. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  35. AUTH_TYPE_PASSWORD,
  36. AUTH_TYPE_GSSAPI, /* always QUIET */
  37. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  38. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  39. } type;
  40. bool need_pw, can_pubkey, can_passwd, can_keyb_inter;
  41. SeatPromptResult spr;
  42. bool tried_pubkey_config, done_agent;
  43. struct ssh_connection_shared_gss_state *shgss;
  44. #ifndef NO_GSSAPI
  45. bool can_gssapi;
  46. bool can_gssapi_keyex_auth;
  47. bool tried_gssapi;
  48. bool tried_gssapi_keyex_auth;
  49. time_t gss_cred_expiry;
  50. Ssh_gss_buf gss_buf;
  51. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  52. Ssh_gss_stat gss_stat;
  53. #endif
  54. bool suppress_wait_for_response_packet;
  55. strbuf *last_methods_string;
  56. bool kbd_inter_refused;
  57. prompts_t *cur_prompt;
  58. uint32_t num_prompts;
  59. const char *username;
  60. char *locally_allocated_username;
  61. char *password;
  62. bool got_username;
  63. strbuf *publickey_blob, *detached_cert_blob, *cert_pubkey_diagnosed;
  64. bool privatekey_available, privatekey_encrypted;
  65. char *publickey_algorithm;
  66. char *publickey_comment;
  67. void *agent_response_to_free;
  68. ptrlen agent_response;
  69. BinarySource asrc[1]; /* for reading SSH agent response */
  70. size_t agent_keys_len;
  71. agent_key *agent_keys;
  72. size_t agent_key_index, agent_key_limit;
  73. ptrlen agent_keyalg;
  74. unsigned signflags;
  75. int len;
  76. PktOut *pktout;
  77. bool is_trivial_auth;
  78. agent_pending_query *auth_agent_query;
  79. bufchain banner;
  80. bufchain_sink banner_bs;
  81. StripCtrlChars *banner_scc;
  82. bool banner_scc_initialised;
  83. char *authplugin_cmd;
  84. Socket *authplugin;
  85. uint32_t authplugin_version;
  86. Plug authplugin_plug;
  87. bufchain authplugin_bc;
  88. strbuf *authplugin_incoming_msg;
  89. size_t authplugin_backlog;
  90. bool authplugin_eof;
  91. bool authplugin_ki_active;
  92. StripCtrlChars *ki_scc;
  93. bool ki_scc_initialised;
  94. bool ki_printed_header;
  95. PacketProtocolLayer ppl;
  96. };
  97. static void ssh2_userauth_free(PacketProtocolLayer *);
  98. static void ssh2_userauth_process_queue(PacketProtocolLayer *);
  99. static bool ssh2_userauth_get_specials(
  100. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx);
  101. static void ssh2_userauth_special_cmd(PacketProtocolLayer *ppl,
  102. SessionSpecialCode code, int arg);
  103. static void ssh2_userauth_reconfigure(PacketProtocolLayer *ppl, Conf *conf);
  104. static void ssh2_userauth_agent_query(struct ssh2_userauth_state *, strbuf *);
  105. static void ssh2_userauth_agent_callback(void *, void *, int);
  106. static void ssh2_userauth_add_sigblob(
  107. struct ssh2_userauth_state *s, PktOut *pkt, ptrlen pkblob, ptrlen sigblob);
  108. static void ssh2_userauth_add_alg_and_publickey(
  109. struct ssh2_userauth_state *s, PktOut *pkt, ptrlen alg, ptrlen pkblob);
  110. static void ssh2_userauth_add_session_id(
  111. struct ssh2_userauth_state *s, strbuf *sigdata);
  112. #ifndef NO_GSSAPI
  113. static PktOut *ssh2_userauth_gss_packet(
  114. struct ssh2_userauth_state *s, const char *authtype);
  115. #endif
  116. static bool ssh2_userauth_ki_setup_prompts(
  117. struct ssh2_userauth_state *s, BinarySource *src, bool plugin);
  118. static bool ssh2_userauth_ki_run_prompts(struct ssh2_userauth_state *s);
  119. static void ssh2_userauth_ki_write_responses(
  120. struct ssh2_userauth_state *s, BinarySink *bs);
  121. static void ssh2_userauth_final_output(PacketProtocolLayer *ppl);
  122. static void ssh2_userauth_print_banner(struct ssh2_userauth_state *s);
  123. static ptrlen workaround_rsa_sha2_cert_userauth(
  124. struct ssh2_userauth_state *s, ptrlen id);
  125. static const PacketProtocolLayerVtable ssh2_userauth_vtable = {
  126. .free = ssh2_userauth_free,
  127. .process_queue = ssh2_userauth_process_queue,
  128. .get_specials = ssh2_userauth_get_specials,
  129. .special_cmd = ssh2_userauth_special_cmd,
  130. .reconfigure = ssh2_userauth_reconfigure,
  131. .queued_data_size = ssh_ppl_default_queued_data_size,
  132. .final_output = ssh2_userauth_final_output,
  133. .name = "ssh-userauth",
  134. };
  135. PacketProtocolLayer *ssh2_userauth_new(
  136. PacketProtocolLayer *successor_layer,
  137. const char *hostname, int port, const char *fullhostname,
  138. Filename *keyfile, Filename *detached_cert_file,
  139. bool show_banner, bool tryagent, bool notrivialauth,
  140. const char *default_username, bool change_username,
  141. bool try_ki_auth, bool try_gssapi_auth, bool try_gssapi_kex_auth,
  142. bool gssapi_fwd, struct ssh_connection_shared_gss_state *shgss,
  143. const char *authplugin_cmd)
  144. {
  145. struct ssh2_userauth_state *s = snew(struct ssh2_userauth_state);
  146. memset(s, 0, sizeof(*s));
  147. s->ppl.vt = &ssh2_userauth_vtable;
  148. s->successor_layer = successor_layer;
  149. s->hostname = dupstr(hostname);
  150. s->port = port;
  151. s->fullhostname = dupstr(fullhostname);
  152. s->keyfile = filename_copy(keyfile);
  153. s->detached_cert_file = filename_copy(detached_cert_file);
  154. s->show_banner = show_banner;
  155. s->tryagent = tryagent;
  156. s->notrivialauth = notrivialauth;
  157. s->default_username = dupstr(default_username);
  158. s->change_username = change_username;
  159. s->try_ki_auth = try_ki_auth;
  160. s->try_gssapi_auth = try_gssapi_auth;
  161. s->try_gssapi_kex_auth = try_gssapi_kex_auth;
  162. s->gssapi_fwd = gssapi_fwd;
  163. s->shgss = shgss;
  164. s->last_methods_string = strbuf_new();
  165. s->is_trivial_auth = true;
  166. bufchain_init(&s->banner);
  167. bufchain_sink_init(&s->banner_bs, &s->banner);
  168. s->authplugin_cmd = dupstr(authplugin_cmd);
  169. bufchain_init(&s->authplugin_bc);
  170. return &s->ppl;
  171. }
  172. void ssh2_userauth_set_transport_layer(PacketProtocolLayer *userauth,
  173. PacketProtocolLayer *transport)
  174. {
  175. struct ssh2_userauth_state *s =
  176. container_of(userauth, struct ssh2_userauth_state, ppl);
  177. s->transport_layer = transport;
  178. }
  179. static void ssh2_userauth_free(PacketProtocolLayer *ppl)
  180. {
  181. struct ssh2_userauth_state *s =
  182. container_of(ppl, struct ssh2_userauth_state, ppl);
  183. bufchain_clear(&s->banner);
  184. if (s->successor_layer)
  185. ssh_ppl_free(s->successor_layer);
  186. if (s->agent_keys) {
  187. for (size_t i = 0; i < s->agent_keys_len; i++) {
  188. strbuf_free(s->agent_keys[i].blob);
  189. strbuf_free(s->agent_keys[i].comment);
  190. }
  191. sfree(s->agent_keys);
  192. }
  193. sfree(s->agent_response_to_free);
  194. if (s->auth_agent_query)
  195. agent_cancel_query(s->auth_agent_query);
  196. filename_free(s->keyfile);
  197. filename_free(s->detached_cert_file);
  198. sfree(s->default_username);
  199. sfree(s->locally_allocated_username);
  200. sfree(s->hostname);
  201. sfree(s->fullhostname);
  202. if (s->cur_prompt)
  203. free_prompts(s->cur_prompt);
  204. sfree(s->publickey_comment);
  205. sfree(s->publickey_algorithm);
  206. if (s->publickey_blob)
  207. strbuf_free(s->publickey_blob);
  208. if (s->detached_cert_blob)
  209. strbuf_free(s->detached_cert_blob);
  210. if (s->cert_pubkey_diagnosed)
  211. strbuf_free(s->cert_pubkey_diagnosed);
  212. strbuf_free(s->last_methods_string);
  213. if (s->banner_scc)
  214. stripctrl_free(s->banner_scc);
  215. if (s->ki_scc)
  216. stripctrl_free(s->ki_scc);
  217. sfree(s->authplugin_cmd);
  218. if (s->authplugin)
  219. sk_close(s->authplugin);
  220. bufchain_clear(&s->authplugin_bc);
  221. if (s->authplugin_incoming_msg)
  222. strbuf_free(s->authplugin_incoming_msg);
  223. sfree(s);
  224. }
  225. static void ssh2_userauth_handle_banner_packet(struct ssh2_userauth_state *s,
  226. PktIn *pktin)
  227. {
  228. if (!s->show_banner)
  229. return;
  230. ptrlen string = get_string(pktin);
  231. if (string.len > BANNER_LIMIT - bufchain_size(&s->banner))
  232. string.len = BANNER_LIMIT - bufchain_size(&s->banner);
  233. if (!s->banner_scc_initialised) {
  234. s->banner_scc = seat_stripctrl_new(
  235. s->ppl.seat, BinarySink_UPCAST(&s->banner_bs), SIC_BANNER);
  236. if (s->banner_scc)
  237. stripctrl_enable_line_limiting(s->banner_scc);
  238. s->banner_scc_initialised = true;
  239. }
  240. if (s->banner_scc)
  241. put_datapl(s->banner_scc, string);
  242. else
  243. put_datapl(&s->banner_bs, string);
  244. }
  245. static void ssh2_userauth_filter_queue(struct ssh2_userauth_state *s)
  246. {
  247. PktIn *pktin;
  248. while ((pktin = pq_peek(s->ppl.in_pq)) != NULL) {
  249. switch (pktin->type) {
  250. case SSH2_MSG_USERAUTH_BANNER:
  251. ssh2_userauth_handle_banner_packet(s, pktin);
  252. pq_pop(s->ppl.in_pq);
  253. break;
  254. default:
  255. return;
  256. }
  257. }
  258. }
  259. static PktIn *ssh2_userauth_pop(struct ssh2_userauth_state *s)
  260. {
  261. ssh2_userauth_filter_queue(s);
  262. return pq_pop(s->ppl.in_pq);
  263. }
  264. static bool ssh2_userauth_signflags(struct ssh2_userauth_state *s,
  265. unsigned *signflags, const char **algname)
  266. {
  267. *signflags = 0; /* default */
  268. const ssh_keyalg *alg = find_pubkey_alg(*algname);
  269. if (!alg)
  270. return false; /* we don't know how to upgrade this */
  271. unsigned supported_flags = ssh_keyalg_supported_flags(alg);
  272. if (s->ppl.bpp->ext_info_rsa_sha512_ok &&
  273. (supported_flags & SSH_AGENT_RSA_SHA2_512)) {
  274. *signflags = SSH_AGENT_RSA_SHA2_512;
  275. } else if (s->ppl.bpp->ext_info_rsa_sha256_ok &&
  276. (supported_flags & SSH_AGENT_RSA_SHA2_256)) {
  277. *signflags = SSH_AGENT_RSA_SHA2_256;
  278. } else {
  279. return false;
  280. }
  281. *algname = ssh_keyalg_alternate_ssh_id(alg, *signflags);
  282. return true;
  283. }
  284. static void authplugin_plug_log(Plug *plug, PlugLogType type, SockAddr *addr,
  285. int port, const char *err_msg, int err_code)
  286. {
  287. struct ssh2_userauth_state *s = container_of(
  288. plug, struct ssh2_userauth_state, authplugin_plug);
  289. PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
  290. if (type == PLUGLOG_PROXY_MSG)
  291. ppl_logevent("%s", err_msg);
  292. }
  293. static void authplugin_plug_closing(
  294. Plug *plug, PlugCloseType type, const char *error_msg)
  295. {
  296. struct ssh2_userauth_state *s = container_of(
  297. plug, struct ssh2_userauth_state, authplugin_plug);
  298. s->authplugin_eof = true;
  299. queue_idempotent_callback(&s->ppl.ic_process_queue);
  300. }
  301. static void authplugin_plug_receive(
  302. Plug *plug, int urgent, const char *data, size_t len)
  303. {
  304. struct ssh2_userauth_state *s = container_of(
  305. plug, struct ssh2_userauth_state, authplugin_plug);
  306. bufchain_add(&s->authplugin_bc, data, len);
  307. queue_idempotent_callback(&s->ppl.ic_process_queue);
  308. }
  309. static void authplugin_plug_sent(Plug *plug, size_t bufsize)
  310. {
  311. struct ssh2_userauth_state *s = container_of(
  312. plug, struct ssh2_userauth_state, authplugin_plug);
  313. s->authplugin_backlog = bufsize;
  314. queue_idempotent_callback(&s->ppl.ic_process_queue);
  315. }
  316. static const PlugVtable authplugin_plugvt = {
  317. .log = authplugin_plug_log,
  318. .closing = authplugin_plug_closing,
  319. .receive = authplugin_plug_receive,
  320. .sent = authplugin_plug_sent,
  321. };
  322. static strbuf *authplugin_newmsg(uint8_t type)
  323. {
  324. strbuf *amsg = strbuf_new_nm();
  325. put_uint32(amsg, 0); /* fill in later */
  326. put_byte(amsg, type);
  327. return amsg;
  328. }
  329. static void authplugin_send_free(struct ssh2_userauth_state *s, strbuf *amsg)
  330. {
  331. PUT_32BIT_MSB_FIRST(amsg->u, amsg->len - 4);
  332. assert(s->authplugin);
  333. s->authplugin_backlog = sk_write(s->authplugin, amsg->u, amsg->len);
  334. strbuf_free(amsg);
  335. }
  336. static bool authplugin_expect_msg(struct ssh2_userauth_state *s,
  337. unsigned *type, BinarySource *src)
  338. {
  339. if (s->authplugin_eof) {
  340. *type = PLUGIN_EOF;
  341. return true;
  342. }
  343. uint8_t len[4];
  344. if (!bufchain_try_fetch(&s->authplugin_bc, len, 4))
  345. return false;
  346. size_t size = GET_32BIT_MSB_FIRST(len);
  347. if (bufchain_size(&s->authplugin_bc) - 4 < size)
  348. return false;
  349. if (s->authplugin_incoming_msg) {
  350. strbuf_clear(s->authplugin_incoming_msg);
  351. } else {
  352. s->authplugin_incoming_msg = strbuf_new_nm();
  353. }
  354. bufchain_consume(&s->authplugin_bc, 4); /* eat length field */
  355. bufchain_fetch_consume(
  356. &s->authplugin_bc, strbuf_append(s->authplugin_incoming_msg, size),
  357. size);
  358. BinarySource_BARE_INIT_PL(
  359. src, ptrlen_from_strbuf(s->authplugin_incoming_msg));
  360. *type = get_byte(src);
  361. if (get_err(src))
  362. *type = PLUGIN_NOTYPE;
  363. return true;
  364. }
  365. static void authplugin_bad_packet(struct ssh2_userauth_state *s,
  366. unsigned type, const char *fmt, ...)
  367. {
  368. strbuf *msg = strbuf_new();
  369. switch (type) {
  370. case PLUGIN_EOF:
  371. put_dataz(msg, "Unexpected end of file from auth helper plugin");
  372. break;
  373. case PLUGIN_NOTYPE:
  374. put_dataz(msg, "Received malformed packet from auth helper plugin "
  375. "(too short to have a type code)");
  376. break;
  377. default:
  378. put_fmt(msg, "Received unknown message type %u "
  379. "from auth helper plugin", type);
  380. break;
  381. #define CASEDECL(name, value) \
  382. case name: \
  383. put_fmt(msg, "Received unexpected %s message from auth helper " \
  384. "plugin", #name); \
  385. break;
  386. AUTHPLUGIN_MSG_NAMES(CASEDECL);
  387. #undef CASEDECL
  388. }
  389. if (fmt) {
  390. put_dataz(msg, " (");
  391. va_list ap;
  392. va_start(ap, fmt);
  393. put_fmt(msg, fmt, ap);
  394. va_end(ap);
  395. put_dataz(msg, ")");
  396. }
  397. ssh_sw_abort(s->ppl.ssh, "%s", msg->s);
  398. strbuf_free(msg);
  399. }
  400. static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl)
  401. {
  402. struct ssh2_userauth_state *s =
  403. container_of(ppl, struct ssh2_userauth_state, ppl);
  404. PktIn *pktin;
  405. ssh2_userauth_filter_queue(s); /* no matter why we were called */
  406. crBegin(s->crState);
  407. #ifndef NO_GSSAPI
  408. s->tried_gssapi = false;
  409. s->tried_gssapi_keyex_auth = false;
  410. #endif
  411. /*
  412. * Misc one-time setup for authentication.
  413. */
  414. s->publickey_blob = NULL;
  415. s->session_id = ssh2_transport_get_session_id(s->transport_layer);
  416. /*
  417. * Load the public half of any configured public key file for
  418. * later use.
  419. */
  420. if (!filename_is_null(s->keyfile)) {
  421. int keytype;
  422. ppl_logevent("Reading key file \"%s\"",
  423. filename_to_str(s->keyfile));
  424. keytype = key_type(s->keyfile);
  425. if (keytype == SSH_KEYTYPE_SSH2 ||
  426. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  427. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  428. const char *error;
  429. s->publickey_blob = strbuf_new();
  430. if (ppk_loadpub_f(s->keyfile, &s->publickey_algorithm,
  431. BinarySink_UPCAST(s->publickey_blob),
  432. &s->publickey_comment, &error)) {
  433. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
  434. if (!s->privatekey_available)
  435. ppl_logevent("Key file contains public key only");
  436. s->privatekey_encrypted = ppk_encrypted_f(s->keyfile, NULL);
  437. } else {
  438. ppl_logevent("Unable to load key (%s)", error);
  439. ppl_printf("Unable to load key file \"%s\" (%s)\r\n",
  440. filename_to_str(s->keyfile), error);
  441. strbuf_free(s->publickey_blob);
  442. s->publickey_blob = NULL;
  443. }
  444. } else {
  445. ppl_logevent("Unable to use this key file (%s)",
  446. key_type_to_str(keytype));
  447. ppl_printf("Unable to use key file \"%s\" (%s)\r\n",
  448. filename_to_str(s->keyfile),
  449. key_type_to_str(keytype));
  450. s->publickey_blob = NULL;
  451. }
  452. }
  453. /*
  454. * If the user provided a detached certificate file, load that.
  455. */
  456. if (!filename_is_null(s->detached_cert_file)) {
  457. char *cert_error = NULL;
  458. strbuf *cert_blob = strbuf_new();
  459. char *algname = NULL;
  460. char *comment = NULL;
  461. ppl_logevent("Reading certificate file \"%s\"",
  462. filename_to_str(s->detached_cert_file));
  463. int keytype = key_type(s->detached_cert_file);
  464. if (!(keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  465. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH)) {
  466. cert_error = dupstr(key_type_to_str(keytype));
  467. goto cert_load_done;
  468. }
  469. const char *error;
  470. bool success = ppk_loadpub_f(
  471. s->detached_cert_file, &algname,
  472. BinarySink_UPCAST(cert_blob), &comment, &error);
  473. if (!success) {
  474. cert_error = dupstr(error);
  475. goto cert_load_done;
  476. }
  477. const ssh_keyalg *certalg = find_pubkey_alg(algname);
  478. if (!certalg) {
  479. cert_error = dupprintf(
  480. "unrecognised certificate type '%s'", algname);
  481. goto cert_load_done;
  482. }
  483. if (!certalg->is_certificate) {
  484. cert_error = dupprintf(
  485. "key type '%s' is not a certificate", certalg->ssh_id);
  486. goto cert_load_done;
  487. }
  488. /* OK, store the certificate blob to substitute for the
  489. * public blob in all publickey auth packets. */
  490. if (s->detached_cert_blob)
  491. strbuf_free(s->detached_cert_blob);
  492. s->detached_cert_blob = cert_blob;
  493. cert_blob = NULL; /* prevent free */
  494. cert_load_done:
  495. if (cert_error) {
  496. ppl_logevent("Unable to use this certificate file (%s)",
  497. cert_error);
  498. ppl_printf(
  499. "Unable to use certificate file \"%s\" (%s)\r\n",
  500. filename_to_str(s->detached_cert_file), cert_error);
  501. sfree(cert_error);
  502. }
  503. if (cert_blob)
  504. strbuf_free(cert_blob);
  505. sfree(algname);
  506. sfree(comment);
  507. }
  508. /*
  509. * Find out about any keys Pageant has (but if there's a public
  510. * key configured, filter out all others).
  511. */
  512. if (s->tryagent && agent_exists()) {
  513. ppl_logevent("Pageant is running. Requesting keys.");
  514. /* Request the keys held by the agent. */
  515. {
  516. strbuf *request = strbuf_new_for_agent_query();
  517. put_byte(request, SSH2_AGENTC_REQUEST_IDENTITIES);
  518. ssh2_userauth_agent_query(s, request);
  519. strbuf_free(request);
  520. crWaitUntilV(!s->auth_agent_query);
  521. }
  522. BinarySource_BARE_INIT_PL(s->asrc, s->agent_response);
  523. get_uint32(s->asrc); /* skip length field */
  524. if (get_byte(s->asrc) == SSH2_AGENT_IDENTITIES_ANSWER) {
  525. size_t nkeys = get_uint32(s->asrc);
  526. size_t origpos = s->asrc->pos;
  527. /*
  528. * Check that the agent response is well formed.
  529. */
  530. for (size_t i = 0; i < nkeys; i++) {
  531. get_string(s->asrc); /* blob */
  532. get_string(s->asrc); /* comment */
  533. if (get_err(s->asrc)) {
  534. ppl_logevent("Pageant's response was truncated");
  535. goto done_agent_query;
  536. }
  537. }
  538. /*
  539. * Copy the list of public-key blobs out of the Pageant
  540. * response.
  541. */
  542. BinarySource_REWIND_TO(s->asrc, origpos);
  543. s->agent_keys_len = nkeys;
  544. s->agent_keys = snewn(s->agent_keys_len, agent_key);
  545. for (size_t i = 0; i < nkeys; i++) {
  546. s->agent_keys[i].blob = strbuf_dup(get_string(s->asrc));
  547. s->agent_keys[i].comment = strbuf_dup(get_string(s->asrc));
  548. /* Also, extract the algorithm string from the start
  549. * of the public-key blob. */
  550. s->agent_keys[i].algorithm = pubkey_blob_to_alg_name(
  551. ptrlen_from_strbuf(s->agent_keys[i].blob));
  552. }
  553. ppl_logevent("Pageant has %"SIZEu" SSH-2 keys", nkeys);
  554. if (s->publickey_blob) {
  555. /*
  556. * If we've been given a specific public key blob,
  557. * filter the list of keys to try from the agent down
  558. * to only that one, or none if it's not there.
  559. */
  560. ptrlen our_blob = ptrlen_from_strbuf(s->publickey_blob);
  561. size_t i;
  562. for (i = 0; i < nkeys; i++) {
  563. if (ptrlen_eq_ptrlen(our_blob, ptrlen_from_strbuf(
  564. s->agent_keys[i].blob)))
  565. break;
  566. }
  567. if (i < nkeys) {
  568. ppl_logevent("Pageant key #%"SIZEu" matches "
  569. "configured key file", i);
  570. s->agent_key_index = i;
  571. s->agent_key_limit = i+1;
  572. } else {
  573. ppl_logevent("Configured key file not in Pageant");
  574. s->agent_key_index = 0;
  575. s->agent_key_limit = 0;
  576. }
  577. } else {
  578. /*
  579. * Otherwise, try them all.
  580. */
  581. s->agent_key_index = 0;
  582. s->agent_key_limit = nkeys;
  583. }
  584. } else {
  585. ppl_logevent("Failed to get reply from Pageant");
  586. }
  587. done_agent_query:;
  588. }
  589. s->got_username = false;
  590. if (*s->authplugin_cmd) {
  591. s->authplugin_plug.vt = &authplugin_plugvt;
  592. s->authplugin = platform_start_subprocess(
  593. s->authplugin_cmd, &s->authplugin_plug, "plugin");
  594. ppl_logevent("Started authentication plugin: %s", s->authplugin_cmd);
  595. }
  596. if (s->authplugin) {
  597. strbuf *amsg = authplugin_newmsg(PLUGIN_INIT);
  598. put_uint32(amsg, PLUGIN_PROTOCOL_MAX_VERSION);
  599. put_stringz(amsg, s->hostname);
  600. put_uint32(amsg, s->port);
  601. put_stringz(amsg, s->username ? s->username : "");
  602. authplugin_send_free(s, amsg);
  603. BinarySource src[1];
  604. unsigned type;
  605. crMaybeWaitUntilV(authplugin_expect_msg(s, &type, src));
  606. switch (type) {
  607. case PLUGIN_INIT_RESPONSE: {
  608. s->authplugin_version = get_uint32(src);
  609. ptrlen username = get_string(src);
  610. if (get_err(src)) {
  611. ssh_sw_abort(s->ppl.ssh, "Received malformed "
  612. "PLUGIN_INIT_RESPONSE from auth helper plugin");
  613. return;
  614. }
  615. if (s->authplugin_version > PLUGIN_PROTOCOL_MAX_VERSION) {
  616. ssh_sw_abort(s->ppl.ssh, "Auth helper plugin announced "
  617. "unsupported version number %"PRIu32,
  618. s->authplugin_version);
  619. return;
  620. }
  621. if (username.len) {
  622. sfree(s->default_username);
  623. s->default_username = mkstr(username);
  624. ppl_logevent("Authentication plugin set username '%s'",
  625. s->default_username);
  626. }
  627. break;
  628. }
  629. case PLUGIN_INIT_FAILURE: {
  630. ptrlen message = get_string(src);
  631. if (get_err(src)) {
  632. ssh_sw_abort(s->ppl.ssh, "Received malformed "
  633. "PLUGIN_INIT_FAILURE from auth helper plugin");
  634. return;
  635. }
  636. /* This is a controlled error, so we need not completely
  637. * abandon the connection. Instead, inform the user, and
  638. * proceed as if the plugin was not present */
  639. ppl_printf("Authentication plugin failed to initialise:\r\n");
  640. seat_set_trust_status(s->ppl.seat, false);
  641. ppl_printf("%.*s\r\n", PTRLEN_PRINTF(message));
  642. seat_set_trust_status(s->ppl.seat, true);
  643. sk_close(s->authplugin);
  644. s->authplugin = NULL;
  645. break;
  646. }
  647. default:
  648. authplugin_bad_packet(s, type, "expected PLUGIN_INIT_RESPONSE or "
  649. "PLUGIN_INIT_FAILURE");
  650. return;
  651. }
  652. }
  653. /*
  654. * We repeat this whole loop, including the username prompt,
  655. * until we manage a successful authentication. If the user
  656. * types the wrong _password_, they can be sent back to the
  657. * beginning to try another username, if this is configured on.
  658. * (If they specify a username in the config, they are never
  659. * asked, even if they do give a wrong password.)
  660. *
  661. * I think this best serves the needs of
  662. *
  663. * - the people who have no configuration, no keys, and just
  664. * want to try repeated (username,password) pairs until they
  665. * type both correctly
  666. *
  667. * - people who have keys and configuration but occasionally
  668. * need to fall back to passwords
  669. *
  670. * - people with a key held in Pageant, who might not have
  671. * logged in to a particular machine before; so they want to
  672. * type a username, and then _either_ their key will be
  673. * accepted, _or_ they will type a password. If they mistype
  674. * the username they will want to be able to get back and
  675. * retype it!
  676. */
  677. while (1) {
  678. /*
  679. * Get a username.
  680. */
  681. if (s->got_username && !s->change_username) {
  682. /*
  683. * We got a username last time round this loop, and
  684. * with change_username turned off we don't try to get
  685. * it again.
  686. */
  687. } else if ((s->username = s->default_username) == NULL) {
  688. s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
  689. s->cur_prompt->to_server = true;
  690. s->cur_prompt->from_server = false;
  691. s->cur_prompt->name = dupstr("SSH login name");
  692. add_prompt(s->cur_prompt, dupstr("login as: "), true);
  693. s->spr = seat_get_userpass_input(
  694. ppl_get_iseat(&s->ppl), s->cur_prompt);
  695. while (s->spr.kind == SPRK_INCOMPLETE) {
  696. crReturnV;
  697. s->spr = seat_get_userpass_input(
  698. ppl_get_iseat(&s->ppl), s->cur_prompt);
  699. }
  700. if (spr_is_abort(s->spr)) {
  701. /*
  702. * seat_get_userpass_input() failed to get a username.
  703. * Terminate.
  704. */
  705. free_prompts(s->cur_prompt);
  706. s->cur_prompt = NULL;
  707. ssh_spr_close(s->ppl.ssh, s->spr, "username prompt");
  708. return;
  709. }
  710. sfree(s->locally_allocated_username); /* for change_username */
  711. s->username = s->locally_allocated_username =
  712. prompt_get_result(s->cur_prompt->prompts[0]);
  713. free_prompts(s->cur_prompt);
  714. s->cur_prompt = NULL;
  715. } else {
  716. if (seat_verbose(s->ppl.seat) || seat_interactive(s->ppl.seat))
  717. ppl_printf("Using username \"%s\".\r\n", s->username);
  718. }
  719. s->got_username = true;
  720. /*
  721. * Send an authentication request using method "none": (a)
  722. * just in case it succeeds, and (b) so that we know what
  723. * authentication methods we can usefully try next.
  724. */
  725. s->ppl.bpp->pls->actx = SSH2_PKTCTX_NOAUTH;
  726. s->pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  727. put_stringz(s->pktout, s->username);
  728. put_stringz(s->pktout, s->successor_layer->vt->name);
  729. put_stringz(s->pktout, "none"); /* method */
  730. pq_push(s->ppl.out_pq, s->pktout);
  731. s->type = AUTH_TYPE_NONE;
  732. s->tried_pubkey_config = false;
  733. s->kbd_inter_refused = false;
  734. s->done_agent = false;
  735. while (1) {
  736. /*
  737. * Wait for the result of the last authentication request,
  738. * unless the request terminated for some reason on our
  739. * own side.
  740. */
  741. if (s->suppress_wait_for_response_packet) {
  742. pktin = NULL;
  743. s->suppress_wait_for_response_packet = false;
  744. } else {
  745. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  746. }
  747. /*
  748. * Now is a convenient point to spew any banner material
  749. * that we've accumulated. (This should ensure that when
  750. * we exit the auth loop, we haven't any left to deal
  751. * with.)
  752. *
  753. * Don't show the banner if we're operating in non-verbose
  754. * non-interactive mode. (It's probably a script, which
  755. * means nobody will read the banner _anyway_, and
  756. * moreover the printing of the banner will screw up
  757. * processing on the output of (say) plink.)
  758. *
  759. * The banner data has been sanitised already by this
  760. * point, but we still need to precede and follow it with
  761. * anti-spoofing header lines.
  762. */
  763. ssh2_userauth_print_banner(s);
  764. if (pktin && pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  765. ppl_logevent("Access granted");
  766. goto userauth_success;
  767. }
  768. if (pktin && pktin->type != SSH2_MSG_USERAUTH_FAILURE &&
  769. s->type != AUTH_TYPE_GSSAPI) {
  770. ssh_proto_error(s->ppl.ssh, "Received unexpected packet "
  771. "in response to authentication request, "
  772. "type %d (%s)", pktin->type,
  773. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  774. s->ppl.bpp->pls->actx,
  775. pktin->type));
  776. return;
  777. }
  778. /*
  779. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  780. * we can look at the string in it and know what we can
  781. * helpfully try next.
  782. */
  783. if (pktin && pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  784. ptrlen methods = get_string(pktin);
  785. bool partial_success = get_bool(pktin);
  786. if (!partial_success) {
  787. /*
  788. * We have received an unequivocal Access
  789. * Denied. This can translate to a variety of
  790. * messages, or no message at all.
  791. *
  792. * For forms of authentication which are attempted
  793. * implicitly, by which I mean without printing
  794. * anything in the window indicating that we're
  795. * trying them, we should never print 'Access
  796. * denied'.
  797. *
  798. * If we do print a message saying that we're
  799. * attempting some kind of authentication, it's OK
  800. * to print a followup message saying it failed -
  801. * but the message may sometimes be more specific
  802. * than simply 'Access denied'.
  803. *
  804. * Additionally, if we'd just tried password
  805. * authentication, we should break out of this
  806. * whole loop so as to go back to the username
  807. * prompt (iff we're configured to allow
  808. * username change attempts).
  809. */
  810. if (s->type == AUTH_TYPE_NONE) {
  811. /* do nothing */
  812. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  813. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  814. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  815. ppl_printf("Server refused our key\r\n");
  816. ppl_logevent("Server refused our key");
  817. } else if (s->type == AUTH_TYPE_PUBLICKEY) {
  818. /* This _shouldn't_ happen except by a
  819. * protocol bug causing client and server to
  820. * disagree on what is a correct signature. */
  821. ppl_printf("Server refused public-key signature"
  822. " despite accepting key!\r\n");
  823. ppl_logevent("Server refused public-key signature"
  824. " despite accepting key!");
  825. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  826. /* quiet, so no ppl_printf */
  827. ppl_logevent("Server refused keyboard-interactive "
  828. "authentication");
  829. } else if (s->type==AUTH_TYPE_GSSAPI) {
  830. /* always quiet, so no ppl_printf */
  831. /* also, the code down in the GSSAPI block has
  832. * already logged this in the Event Log */
  833. } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
  834. ppl_logevent("Keyboard-interactive authentication "
  835. "failed");
  836. ppl_printf("Access denied\r\n");
  837. } else {
  838. assert(s->type == AUTH_TYPE_PASSWORD);
  839. ppl_logevent("Password authentication failed");
  840. ppl_printf("Access denied\r\n");
  841. if (s->change_username) {
  842. /* XXX perhaps we should allow
  843. * keyboard-interactive to do this too? */
  844. goto try_new_username;
  845. }
  846. }
  847. } else {
  848. ppl_printf("Further authentication required\r\n");
  849. ppl_logevent("Further authentication required");
  850. }
  851. /*
  852. * Save the methods string for use in error messages.
  853. */
  854. strbuf_clear(s->last_methods_string);
  855. put_datapl(s->last_methods_string, methods);
  856. /*
  857. * Scan it for method identifiers we know about.
  858. */
  859. bool srv_pubkey = false, srv_passwd = false;
  860. bool srv_keyb_inter = false;
  861. #ifndef NO_GSSAPI
  862. bool srv_gssapi = false, srv_gssapi_keyex_auth = false;
  863. #endif
  864. for (ptrlen method; get_commasep_word(&methods, &method) ;) {
  865. if (ptrlen_eq_string(method, "publickey"))
  866. srv_pubkey = true;
  867. else if (ptrlen_eq_string(method, "password"))
  868. srv_passwd = true;
  869. else if (ptrlen_eq_string(method, "keyboard-interactive"))
  870. srv_keyb_inter = true;
  871. #ifndef NO_GSSAPI
  872. else if (ptrlen_eq_string(method, "gssapi-with-mic"))
  873. srv_gssapi = true;
  874. else if (ptrlen_eq_string(method, "gssapi-keyex"))
  875. srv_gssapi_keyex_auth = true;
  876. #endif
  877. }
  878. /*
  879. * And combine those flags with our own configuration
  880. * and context to set the main can_foo variables.
  881. */
  882. s->can_pubkey = srv_pubkey;
  883. s->can_passwd = srv_passwd;
  884. s->can_keyb_inter = s->try_ki_auth && srv_keyb_inter;
  885. #ifndef NO_GSSAPI
  886. s->can_gssapi = s->try_gssapi_auth && srv_gssapi &&
  887. s->shgss->libs->nlibraries > 0;
  888. s->can_gssapi_keyex_auth = s->try_gssapi_kex_auth &&
  889. srv_gssapi_keyex_auth &&
  890. s->shgss->libs->nlibraries > 0 && s->shgss->ctx;
  891. #endif
  892. }
  893. s->ppl.bpp->pls->actx = SSH2_PKTCTX_NOAUTH;
  894. #ifndef NO_GSSAPI
  895. if (s->can_gssapi_keyex_auth && !s->tried_gssapi_keyex_auth) {
  896. /* gssapi-keyex authentication */
  897. s->type = AUTH_TYPE_GSSAPI;
  898. s->tried_gssapi_keyex_auth = true;
  899. s->ppl.bpp->pls->actx = SSH2_PKTCTX_GSSAPI;
  900. if (s->shgss->lib->gsslogmsg)
  901. ppl_logevent("%s", s->shgss->lib->gsslogmsg);
  902. ppl_logevent("Trying gssapi-keyex...");
  903. s->pktout = ssh2_userauth_gss_packet(s, "gssapi-keyex");
  904. pq_push(s->ppl.out_pq, s->pktout);
  905. s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
  906. s->shgss->ctx = NULL;
  907. continue;
  908. } else
  909. #endif /* NO_GSSAPI */
  910. if (s->can_pubkey && !s->done_agent &&
  911. s->agent_key_index < s->agent_key_limit) {
  912. /*
  913. * Attempt public-key authentication using a key from Pageant.
  914. */
  915. s->agent_keyalg = s->agent_keys[s->agent_key_index].algorithm;
  916. char *alg_tmp = mkstr(s->agent_keyalg);
  917. const char *newalg = alg_tmp;
  918. if (ssh2_userauth_signflags(s, &s->signflags, &newalg))
  919. s->agent_keyalg = ptrlen_from_asciz(newalg);
  920. sfree(alg_tmp);
  921. s->ppl.bpp->pls->actx = SSH2_PKTCTX_PUBLICKEY;
  922. ppl_logevent("Trying Pageant key #%"SIZEu, s->agent_key_index);
  923. /* See if server will accept it */
  924. s->pktout = ssh_bpp_new_pktout(
  925. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  926. put_stringz(s->pktout, s->username);
  927. put_stringz(s->pktout, s->successor_layer->vt->name);
  928. put_stringz(s->pktout, "publickey");
  929. /* method */
  930. put_bool(s->pktout, false); /* no signature included */
  931. ssh2_userauth_add_alg_and_publickey(
  932. s, s->pktout, s->agent_keyalg, ptrlen_from_strbuf(
  933. s->agent_keys[s->agent_key_index].blob));
  934. pq_push(s->ppl.out_pq, s->pktout);
  935. s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
  936. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  937. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  938. /* Offer of key refused, presumably via
  939. * USERAUTH_FAILURE. Requeue for the next iteration. */
  940. pq_push_front(s->ppl.in_pq, pktin);
  941. } else {
  942. strbuf *agentreq, *sigdata;
  943. ptrlen comment = ptrlen_from_strbuf(
  944. s->agent_keys[s->agent_key_index].comment);
  945. if (seat_verbose(s->ppl.seat))
  946. ppl_printf("Authenticating with public key "
  947. "\"%.*s\" from agent\r\n",
  948. PTRLEN_PRINTF(comment));
  949. /*
  950. * Server is willing to accept the key.
  951. * Construct a SIGN_REQUEST.
  952. */
  953. s->pktout = ssh_bpp_new_pktout(
  954. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  955. put_stringz(s->pktout, s->username);
  956. put_stringz(s->pktout, s->successor_layer->vt->name);
  957. put_stringz(s->pktout, "publickey");
  958. /* method */
  959. put_bool(s->pktout, true); /* signature included */
  960. ssh2_userauth_add_alg_and_publickey(
  961. s, s->pktout, s->agent_keyalg, ptrlen_from_strbuf(
  962. s->agent_keys[s->agent_key_index].blob));
  963. /* Ask agent for signature. */
  964. agentreq = strbuf_new_for_agent_query();
  965. put_byte(agentreq, SSH2_AGENTC_SIGN_REQUEST);
  966. put_stringpl(agentreq, ptrlen_from_strbuf(
  967. s->agent_keys[s->agent_key_index].blob));
  968. /* Now the data to be signed... */
  969. sigdata = strbuf_new();
  970. ssh2_userauth_add_session_id(s, sigdata);
  971. put_data(sigdata, s->pktout->data + 5,
  972. s->pktout->length - 5);
  973. put_stringsb(agentreq, sigdata);
  974. /* And finally the flags word. */
  975. put_uint32(agentreq, s->signflags);
  976. ssh2_userauth_agent_query(s, agentreq);
  977. strbuf_free(agentreq);
  978. crWaitUntilV(!s->auth_agent_query);
  979. if (s->agent_response.ptr) {
  980. ptrlen sigblob;
  981. BinarySource src[1];
  982. BinarySource_BARE_INIT(src, s->agent_response.ptr,
  983. s->agent_response.len);
  984. get_uint32(src); /* skip length field */
  985. if (get_byte(src) == SSH2_AGENT_SIGN_RESPONSE &&
  986. (sigblob = get_string(src), !get_err(src))) {
  987. ppl_logevent("Sending Pageant's response");
  988. ssh2_userauth_add_sigblob(
  989. s, s->pktout,
  990. ptrlen_from_strbuf(
  991. s->agent_keys[s->agent_key_index].blob),
  992. sigblob);
  993. pq_push(s->ppl.out_pq, s->pktout);
  994. s->type = AUTH_TYPE_PUBLICKEY;
  995. s->is_trivial_auth = false;
  996. } else {
  997. ppl_logevent("Pageant refused signing request");
  998. ppl_printf("Pageant failed to "
  999. "provide a signature\r\n");
  1000. s->suppress_wait_for_response_packet = true;
  1001. ssh_free_pktout(s->pktout);
  1002. }
  1003. } else {
  1004. ppl_logevent("Pageant failed to respond to "
  1005. "signing request");
  1006. ppl_printf("Pageant failed to "
  1007. "respond to signing request\r\n");
  1008. s->suppress_wait_for_response_packet = true;
  1009. ssh_free_pktout(s->pktout);
  1010. }
  1011. }
  1012. /* Do we have any keys left to try? */
  1013. if (++s->agent_key_index >= s->agent_key_limit)
  1014. s->done_agent = true;
  1015. } else if (s->can_pubkey && s->publickey_blob &&
  1016. s->privatekey_available && !s->tried_pubkey_config) {
  1017. ssh2_userkey *key; /* not live over crReturn */
  1018. char *passphrase; /* not live over crReturn */
  1019. s->ppl.bpp->pls->actx = SSH2_PKTCTX_PUBLICKEY;
  1020. s->tried_pubkey_config = true;
  1021. /*
  1022. * Try the public key supplied in the configuration.
  1023. *
  1024. * First, try to upgrade its algorithm.
  1025. */
  1026. const char *newalg = s->publickey_algorithm;
  1027. if (ssh2_userauth_signflags(s, &s->signflags, &newalg)) {
  1028. sfree(s->publickey_algorithm);
  1029. s->publickey_algorithm = dupstr(newalg);
  1030. }
  1031. /*
  1032. * Offer the public blob to see if the server is willing to
  1033. * accept it.
  1034. */
  1035. s->pktout = ssh_bpp_new_pktout(
  1036. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1037. put_stringz(s->pktout, s->username);
  1038. put_stringz(s->pktout, s->successor_layer->vt->name);
  1039. put_stringz(s->pktout, "publickey"); /* method */
  1040. put_bool(s->pktout, false);
  1041. /* no signature included */
  1042. ssh2_userauth_add_alg_and_publickey(
  1043. s, s->pktout, ptrlen_from_asciz(s->publickey_algorithm),
  1044. ptrlen_from_strbuf(s->publickey_blob));
  1045. pq_push(s->ppl.out_pq, s->pktout);
  1046. ppl_logevent("Offered public key");
  1047. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1048. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  1049. /* Key refused. Give up. */
  1050. pq_push_front(s->ppl.in_pq, pktin);
  1051. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  1052. continue; /* process this new message */
  1053. }
  1054. ppl_logevent("Offer of public key accepted");
  1055. /*
  1056. * Actually attempt a serious authentication using
  1057. * the key.
  1058. */
  1059. if (seat_verbose(s->ppl.seat))
  1060. ppl_printf("Authenticating with public key \"%s\"\r\n",
  1061. s->publickey_comment);
  1062. key = NULL;
  1063. while (!key) {
  1064. const char *error; /* not live over crReturn */
  1065. if (s->privatekey_encrypted) {
  1066. /*
  1067. * Get a passphrase from the user.
  1068. */
  1069. s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
  1070. s->cur_prompt->to_server = false;
  1071. s->cur_prompt->from_server = false;
  1072. s->cur_prompt->name = dupstr("SSH key passphrase");
  1073. add_prompt(s->cur_prompt,
  1074. dupprintf("Passphrase for key \"%s\": ",
  1075. s->publickey_comment),
  1076. false);
  1077. s->spr = seat_get_userpass_input(
  1078. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1079. while (s->spr.kind == SPRK_INCOMPLETE) {
  1080. crReturnV;
  1081. s->spr = seat_get_userpass_input(
  1082. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1083. }
  1084. if (spr_is_abort(s->spr)) {
  1085. /* Failed to get a passphrase. Terminate. */
  1086. free_prompts(s->cur_prompt);
  1087. s->cur_prompt = NULL;
  1088. ssh_bpp_queue_disconnect(
  1089. s->ppl.bpp, "Unable to authenticate",
  1090. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1091. ssh_spr_close(s->ppl.ssh, s->spr,
  1092. "passphrase prompt");
  1093. return;
  1094. }
  1095. passphrase =
  1096. prompt_get_result(s->cur_prompt->prompts[0]);
  1097. free_prompts(s->cur_prompt);
  1098. s->cur_prompt = NULL;
  1099. } else {
  1100. passphrase = NULL; /* no passphrase needed */
  1101. }
  1102. /*
  1103. * Try decrypting the key.
  1104. */
  1105. key = ppk_load_f(s->keyfile, passphrase, &error);
  1106. if (passphrase) {
  1107. /* burn the evidence */
  1108. smemclr(passphrase, strlen(passphrase));
  1109. sfree(passphrase);
  1110. }
  1111. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  1112. if (passphrase &&
  1113. (key == SSH2_WRONG_PASSPHRASE)) {
  1114. ppl_printf("Wrong passphrase\r\n");
  1115. key = NULL;
  1116. /* and loop again */
  1117. } else {
  1118. ppl_printf("Unable to load private key (%s)\r\n",
  1119. error);
  1120. key = NULL;
  1121. s->suppress_wait_for_response_packet = true;
  1122. break; /* try something else */
  1123. }
  1124. } else {
  1125. /* FIXME: if we ever support variable signature
  1126. * flags, this is somewhere they'll need to be
  1127. * put */
  1128. char *invalid = ssh_key_invalid(key->key, 0);
  1129. if (invalid) {
  1130. ppl_printf("Cannot use this private key (%s)\r\n",
  1131. invalid);
  1132. ssh_key_free(key->key);
  1133. sfree(key->comment);
  1134. sfree(key);
  1135. sfree(invalid);
  1136. key = NULL;
  1137. s->suppress_wait_for_response_packet = true;
  1138. break; /* try something else */
  1139. }
  1140. }
  1141. }
  1142. if (key) {
  1143. strbuf *pkblob, *sigdata, *sigblob;
  1144. /*
  1145. * We have loaded the private key and the server
  1146. * has announced that it's willing to accept it.
  1147. * Hallelujah. Generate a signature and send it.
  1148. */
  1149. s->pktout = ssh_bpp_new_pktout(
  1150. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1151. put_stringz(s->pktout, s->username);
  1152. put_stringz(s->pktout, s->successor_layer->vt->name);
  1153. put_stringz(s->pktout, "publickey"); /* method */
  1154. put_bool(s->pktout, true); /* signature follows */
  1155. pkblob = strbuf_new();
  1156. ssh_key_public_blob(key->key, BinarySink_UPCAST(pkblob));
  1157. ssh2_userauth_add_alg_and_publickey(
  1158. s, s->pktout,
  1159. ptrlen_from_asciz(s->publickey_algorithm),
  1160. ptrlen_from_strbuf(pkblob));
  1161. /*
  1162. * The data to be signed is:
  1163. *
  1164. * string session-id
  1165. *
  1166. * followed by everything so far placed in the
  1167. * outgoing packet.
  1168. */
  1169. sigdata = strbuf_new();
  1170. ssh2_userauth_add_session_id(s, sigdata);
  1171. put_data(sigdata, s->pktout->data + 5,
  1172. s->pktout->length - 5);
  1173. sigblob = strbuf_new();
  1174. ssh_key_sign(key->key, ptrlen_from_strbuf(sigdata),
  1175. s->signflags, BinarySink_UPCAST(sigblob));
  1176. strbuf_free(sigdata);
  1177. ssh2_userauth_add_sigblob(
  1178. s, s->pktout, ptrlen_from_strbuf(pkblob),
  1179. ptrlen_from_strbuf(sigblob));
  1180. strbuf_free(pkblob);
  1181. strbuf_free(sigblob);
  1182. pq_push(s->ppl.out_pq, s->pktout);
  1183. ppl_logevent("Sent public key signature");
  1184. s->type = AUTH_TYPE_PUBLICKEY;
  1185. ssh_key_free(key->key);
  1186. sfree(key->comment);
  1187. sfree(key);
  1188. s->is_trivial_auth = false;
  1189. }
  1190. #ifndef NO_GSSAPI
  1191. } else if (s->can_gssapi && !s->tried_gssapi) {
  1192. /* gssapi-with-mic authentication */
  1193. ptrlen data;
  1194. s->type = AUTH_TYPE_GSSAPI;
  1195. s->tried_gssapi = true;
  1196. s->ppl.bpp->pls->actx = SSH2_PKTCTX_GSSAPI;
  1197. if (s->shgss->lib->gsslogmsg)
  1198. ppl_logevent("%s", s->shgss->lib->gsslogmsg);
  1199. /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
  1200. ppl_logevent("Trying gssapi-with-mic...");
  1201. s->pktout = ssh_bpp_new_pktout(
  1202. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1203. put_stringz(s->pktout, s->username);
  1204. put_stringz(s->pktout, s->successor_layer->vt->name);
  1205. put_stringz(s->pktout, "gssapi-with-mic");
  1206. ppl_logevent("Attempting GSSAPI authentication");
  1207. /* add mechanism info */
  1208. s->shgss->lib->indicate_mech(s->shgss->lib, &s->gss_buf);
  1209. /* number of GSSAPI mechanisms */
  1210. put_uint32(s->pktout, 1);
  1211. /* length of OID + 2 */
  1212. put_uint32(s->pktout, s->gss_buf.length + 2);
  1213. put_byte(s->pktout, SSH2_GSS_OIDTYPE);
  1214. /* length of OID */
  1215. put_byte(s->pktout, s->gss_buf.length);
  1216. put_data(s->pktout, s->gss_buf.value, s->gss_buf.length);
  1217. pq_push(s->ppl.out_pq, s->pktout);
  1218. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1219. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
  1220. ppl_logevent("GSSAPI authentication request refused");
  1221. pq_push_front(s->ppl.in_pq, pktin);
  1222. continue;
  1223. }
  1224. /* check returned packet ... */
  1225. data = get_string(pktin);
  1226. s->gss_rcvtok.value = (char *)data.ptr;
  1227. s->gss_rcvtok.length = data.len;
  1228. if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
  1229. ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
  1230. ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
  1231. memcmp((char *)s->gss_rcvtok.value + 2,
  1232. s->gss_buf.value,s->gss_buf.length) ) {
  1233. ppl_logevent("GSSAPI authentication - wrong response "
  1234. "from server");
  1235. continue;
  1236. }
  1237. /* Import server name if not cached from KEX */
  1238. if (s->shgss->srv_name == GSS_C_NO_NAME) {
  1239. s->gss_stat = s->shgss->lib->import_name(
  1240. s->shgss->lib, s->fullhostname, &s->shgss->srv_name);
  1241. if (s->gss_stat != SSH_GSS_OK) {
  1242. if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
  1243. ppl_logevent("GSSAPI import name failed -"
  1244. " Bad service name");
  1245. else
  1246. ppl_logevent("GSSAPI import name failed");
  1247. continue;
  1248. }
  1249. }
  1250. /* Allocate our gss_ctx */
  1251. s->gss_stat = s->shgss->lib->acquire_cred(
  1252. s->shgss->lib, &s->shgss->ctx, NULL);
  1253. if (s->gss_stat != SSH_GSS_OK) {
  1254. ppl_logevent("GSSAPI authentication failed to get "
  1255. "credentials");
  1256. /* The failure was on our side, so the server
  1257. * won't be sending a response packet indicating
  1258. * failure. Avoid waiting for it next time round
  1259. * the loop. */
  1260. s->suppress_wait_for_response_packet = true;
  1261. continue;
  1262. }
  1263. /* initial tokens are empty */
  1264. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  1265. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  1266. /* now enter the loop */
  1267. do {
  1268. /*
  1269. * When acquire_cred yields no useful expiration, go with
  1270. * the service ticket expiration.
  1271. */
  1272. s->gss_stat = s->shgss->lib->init_sec_context(
  1273. s->shgss->lib,
  1274. &s->shgss->ctx,
  1275. s->shgss->srv_name,
  1276. s->gssapi_fwd,
  1277. &s->gss_rcvtok,
  1278. &s->gss_sndtok,
  1279. NULL,
  1280. NULL);
  1281. if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
  1282. s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
  1283. ppl_logevent("GSSAPI authentication initialisation "
  1284. "failed");
  1285. if (s->shgss->lib->display_status(
  1286. s->shgss->lib, s->shgss->ctx, &s->gss_buf)
  1287. == SSH_GSS_OK) {
  1288. ppl_logevent("%s", (char *)s->gss_buf.value);
  1289. sfree(s->gss_buf.value);
  1290. }
  1291. pq_push_front(s->ppl.in_pq, pktin);
  1292. break;
  1293. }
  1294. ppl_logevent("GSSAPI authentication initialised");
  1295. /*
  1296. * Client and server now exchange tokens until GSSAPI
  1297. * no longer says CONTINUE_NEEDED
  1298. */
  1299. if (s->gss_sndtok.length != 0) {
  1300. s->is_trivial_auth = false;
  1301. s->pktout =
  1302. ssh_bpp_new_pktout(
  1303. s->ppl.bpp, SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
  1304. put_string(s->pktout,
  1305. s->gss_sndtok.value, s->gss_sndtok.length);
  1306. pq_push(s->ppl.out_pq, s->pktout);
  1307. s->shgss->lib->free_tok(s->shgss->lib, &s->gss_sndtok);
  1308. }
  1309. if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
  1310. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1311. if (pktin->type == SSH2_MSG_USERAUTH_GSSAPI_ERRTOK) {
  1312. /*
  1313. * Per RFC 4462 section 3.9, this packet
  1314. * type MUST immediately precede an
  1315. * ordinary USERAUTH_FAILURE.
  1316. *
  1317. * We currently don't know how to do
  1318. * anything with the GSSAPI error token
  1319. * contained in this packet, so we ignore
  1320. * it and just wait for the following
  1321. * FAILURE.
  1322. */
  1323. crMaybeWaitUntilV(
  1324. (pktin = ssh2_userauth_pop(s)) != NULL);
  1325. if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
  1326. ssh_proto_error(
  1327. s->ppl.ssh, "Received unexpected packet "
  1328. "after SSH_MSG_USERAUTH_GSSAPI_ERRTOK "
  1329. "(expected SSH_MSG_USERAUTH_FAILURE): "
  1330. "type %d (%s)", pktin->type,
  1331. ssh2_pkt_type(s->ppl.bpp->pls->kctx,
  1332. s->ppl.bpp->pls->actx,
  1333. pktin->type));
  1334. return;
  1335. }
  1336. }
  1337. if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  1338. ppl_logevent("GSSAPI authentication failed");
  1339. s->gss_stat = SSH_GSS_FAILURE;
  1340. pq_push_front(s->ppl.in_pq, pktin);
  1341. break;
  1342. } else if (pktin->type !=
  1343. SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
  1344. ppl_logevent("GSSAPI authentication -"
  1345. " bad server response");
  1346. s->gss_stat = SSH_GSS_FAILURE;
  1347. break;
  1348. }
  1349. data = get_string(pktin);
  1350. s->gss_rcvtok.value = (char *)data.ptr;
  1351. s->gss_rcvtok.length = data.len;
  1352. }
  1353. } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  1354. if (s->gss_stat != SSH_GSS_OK) {
  1355. s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
  1356. continue;
  1357. }
  1358. ppl_logevent("GSSAPI authentication loop finished OK");
  1359. /* Now send the MIC */
  1360. s->pktout = ssh2_userauth_gss_packet(s, "gssapi-with-mic");
  1361. pq_push(s->ppl.out_pq, s->pktout);
  1362. s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
  1363. continue;
  1364. #endif
  1365. } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
  1366. /*
  1367. * Keyboard-interactive authentication.
  1368. */
  1369. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  1370. s->ppl.bpp->pls->actx = SSH2_PKTCTX_KBDINTER;
  1371. s->pktout = ssh_bpp_new_pktout(
  1372. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1373. put_stringz(s->pktout, s->username);
  1374. put_stringz(s->pktout, s->successor_layer->vt->name);
  1375. put_stringz(s->pktout, "keyboard-interactive");
  1376. /* method */
  1377. put_stringz(s->pktout, ""); /* lang */
  1378. put_stringz(s->pktout, ""); /* submethods */
  1379. pq_push(s->ppl.out_pq, s->pktout);
  1380. ppl_logevent("Attempting keyboard-interactive authentication");
  1381. if (s->authplugin) {
  1382. strbuf *amsg = authplugin_newmsg(PLUGIN_PROTOCOL);
  1383. put_stringz(amsg, "keyboard-interactive");
  1384. authplugin_send_free(s, amsg);
  1385. BinarySource src[1];
  1386. unsigned type;
  1387. crMaybeWaitUntilV(authplugin_expect_msg(s, &type, src));
  1388. switch (type) {
  1389. case PLUGIN_PROTOCOL_REJECT: {
  1390. ptrlen message = PTRLEN_LITERAL("");
  1391. if (s->authplugin_version >= 2) {
  1392. /* draft protocol didn't include a message here */
  1393. message = get_string(src);
  1394. }
  1395. if (get_err(src)) {
  1396. ssh_sw_abort(s->ppl.ssh, "Received malformed "
  1397. "PLUGIN_PROTOCOL_REJECT from auth "
  1398. "helper plugin");
  1399. return;
  1400. }
  1401. if (message.len) {
  1402. /* If the plugin sent a message about
  1403. * _why_ it didn't want to do k-i, pass
  1404. * that message on to the user. (It might
  1405. * say, for example, what went wrong when
  1406. * it tried to open its config file.) */
  1407. ppl_printf("Authentication plugin failed to set "
  1408. "up keyboard-interactive "
  1409. "authentication:\r\n");
  1410. seat_set_trust_status(s->ppl.seat, false);
  1411. ppl_printf("%.*s\r\n", PTRLEN_PRINTF(message));
  1412. seat_set_trust_status(s->ppl.seat, true);
  1413. ppl_logevent("Authentication plugin declined to "
  1414. "help with keyboard-interactive: "
  1415. "%.*s", PTRLEN_PRINTF(message));
  1416. } else {
  1417. ppl_logevent("Authentication plugin declined to "
  1418. "help with keyboard-interactive");
  1419. }
  1420. s->authplugin_ki_active = false;
  1421. break;
  1422. }
  1423. case PLUGIN_PROTOCOL_ACCEPT:
  1424. s->authplugin_ki_active = true;
  1425. ppl_logevent("Authentication plugin agreed to help "
  1426. "with keyboard-interactive");
  1427. break;
  1428. default:
  1429. authplugin_bad_packet(
  1430. s, type, "expected PLUGIN_PROTOCOL_ACCEPT or "
  1431. "PLUGIN_PROTOCOL_REJECT");
  1432. return;
  1433. }
  1434. } else {
  1435. s->authplugin_ki_active = false;
  1436. }
  1437. if (!s->ki_scc_initialised) {
  1438. s->ki_scc = seat_stripctrl_new(
  1439. s->ppl.seat, NULL, SIC_KI_PROMPTS);
  1440. if (s->ki_scc)
  1441. stripctrl_enable_line_limiting(s->ki_scc);
  1442. s->ki_scc_initialised = true;
  1443. }
  1444. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1445. if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  1446. /* Server is not willing to do keyboard-interactive
  1447. * at all (or, bizarrely but legally, accepts the
  1448. * user without actually issuing any prompts).
  1449. * Give up on it entirely. */
  1450. pq_push_front(s->ppl.in_pq, pktin);
  1451. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  1452. s->kbd_inter_refused = true; /* don't try it again */
  1453. continue;
  1454. }
  1455. s->ki_printed_header = false;
  1456. /*
  1457. * Loop while we still have prompts to send to the user.
  1458. */
  1459. if (!s->authplugin_ki_active) {
  1460. /*
  1461. * The simple case: INFO_REQUESTs are passed on to
  1462. * the user, and responses are sent straight back
  1463. * to the SSH server.
  1464. */
  1465. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  1466. if (!ssh2_userauth_ki_setup_prompts(
  1467. s, BinarySource_UPCAST(pktin), false))
  1468. return;
  1469. crMaybeWaitUntilV(ssh2_userauth_ki_run_prompts(s));
  1470. if (spr_is_abort(s->spr)) {
  1471. /*
  1472. * Failed to get responses. Terminate.
  1473. */
  1474. free_prompts(s->cur_prompt);
  1475. s->cur_prompt = NULL;
  1476. ssh_bpp_queue_disconnect(
  1477. s->ppl.bpp, "Unable to authenticate",
  1478. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1479. ssh_spr_close(s->ppl.ssh, s->spr, "keyboard-"
  1480. "interactive authentication prompt");
  1481. return;
  1482. }
  1483. /*
  1484. * Send the response(s) to the server.
  1485. */
  1486. s->pktout = ssh_bpp_new_pktout(
  1487. s->ppl.bpp, SSH2_MSG_USERAUTH_INFO_RESPONSE);
  1488. ssh2_userauth_ki_write_responses(
  1489. s, BinarySink_UPCAST(s->pktout));
  1490. s->pktout->minlen = 256;
  1491. pq_push(s->ppl.out_pq, s->pktout);
  1492. /*
  1493. * Get the next packet in case it's another
  1494. * INFO_REQUEST.
  1495. */
  1496. crMaybeWaitUntilV(
  1497. (pktin = ssh2_userauth_pop(s)) != NULL);
  1498. }
  1499. } else {
  1500. /*
  1501. * The case where a plugin is involved:
  1502. * INFO_REQUEST from the server is sent to the
  1503. * plugin, which sends responses that we hand back
  1504. * to the server. But in the meantime, the plugin
  1505. * might send USER_REQUEST for us to pass to the
  1506. * user, and then we send responses to that.
  1507. */
  1508. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  1509. strbuf *amsg = authplugin_newmsg(
  1510. PLUGIN_KI_SERVER_REQUEST);
  1511. put_datapl(amsg, get_data(pktin, get_avail(pktin)));
  1512. authplugin_send_free(s, amsg);
  1513. BinarySource src[1];
  1514. unsigned type;
  1515. while (true) {
  1516. crMaybeWaitUntilV(authplugin_expect_msg(
  1517. s, &type, src));
  1518. if (type != PLUGIN_KI_USER_REQUEST)
  1519. break;
  1520. if (!ssh2_userauth_ki_setup_prompts(s, src, true))
  1521. return;
  1522. crMaybeWaitUntilV(ssh2_userauth_ki_run_prompts(s));
  1523. if (spr_is_abort(s->spr)) {
  1524. /*
  1525. * Failed to get responses. Terminate.
  1526. */
  1527. free_prompts(s->cur_prompt);
  1528. s->cur_prompt = NULL;
  1529. ssh_bpp_queue_disconnect(
  1530. s->ppl.bpp, "Unable to authenticate",
  1531. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1532. ssh_spr_close(
  1533. s->ppl.ssh, s->spr, "keyboard-"
  1534. "interactive authentication prompt");
  1535. return;
  1536. }
  1537. /*
  1538. * Send the responses on to the plugin.
  1539. */
  1540. strbuf *amsg = authplugin_newmsg(
  1541. PLUGIN_KI_USER_RESPONSE);
  1542. ssh2_userauth_ki_write_responses(
  1543. s, BinarySink_UPCAST(amsg));
  1544. authplugin_send_free(s, amsg);
  1545. }
  1546. if (type != PLUGIN_KI_SERVER_RESPONSE) {
  1547. authplugin_bad_packet(
  1548. s, type, "expected PLUGIN_KI_SERVER_RESPONSE "
  1549. "or PLUGIN_PROTOCOL_USER_REQUEST");
  1550. return;
  1551. }
  1552. s->pktout = ssh_bpp_new_pktout(
  1553. s->ppl.bpp, SSH2_MSG_USERAUTH_INFO_RESPONSE);
  1554. put_datapl(s->pktout, get_data(src, get_avail(src)));
  1555. s->pktout->minlen = 256;
  1556. pq_push(s->ppl.out_pq, s->pktout);
  1557. /*
  1558. * Get the next packet in case it's another
  1559. * INFO_REQUEST.
  1560. */
  1561. crMaybeWaitUntilV(
  1562. (pktin = ssh2_userauth_pop(s)) != NULL);
  1563. }
  1564. }
  1565. /*
  1566. * Print our trailer line, if we printed a header.
  1567. */
  1568. if (s->ki_printed_header) {
  1569. seat_set_trust_status(s->ppl.seat, true);
  1570. seat_antispoof_msg(
  1571. ppl_get_iseat(&s->ppl),
  1572. (s->authplugin_ki_active ?
  1573. "End of keyboard-interactive prompts from plugin" :
  1574. "End of keyboard-interactive prompts from server"));
  1575. }
  1576. /*
  1577. * We should have SUCCESS or FAILURE now.
  1578. */
  1579. pq_push_front(s->ppl.in_pq, pktin);
  1580. if (s->authplugin_ki_active) {
  1581. /*
  1582. * As our last communication with the plugin, tell
  1583. * it whether the k-i authentication succeeded.
  1584. */
  1585. int plugin_msg = -1;
  1586. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  1587. plugin_msg = PLUGIN_AUTH_SUCCESS;
  1588. } else if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  1589. /*
  1590. * Peek in the failure packet to see if it's a
  1591. * partial success.
  1592. */
  1593. BinarySource src[1];
  1594. BinarySource_BARE_INIT(
  1595. src, get_ptr(pktin), get_avail(pktin));
  1596. get_string(pktin); /* skip methods */
  1597. bool partial_success = get_bool(pktin);
  1598. if (!get_err(src)) {
  1599. plugin_msg = partial_success ?
  1600. PLUGIN_AUTH_SUCCESS : PLUGIN_AUTH_FAILURE;
  1601. }
  1602. }
  1603. if (plugin_msg >= 0) {
  1604. strbuf *amsg = authplugin_newmsg(plugin_msg);
  1605. authplugin_send_free(s, amsg);
  1606. /* Wait until we've actually sent it, in case
  1607. * we close the connection to the plugin
  1608. * before that outgoing message has left our
  1609. * own buffers */
  1610. crMaybeWaitUntilV(s->authplugin_backlog == 0);
  1611. }
  1612. }
  1613. } else if (s->can_passwd) {
  1614. s->is_trivial_auth = false;
  1615. /*
  1616. * Plain old password authentication.
  1617. */
  1618. bool changereq_first_time; /* not live over crReturn */
  1619. s->ppl.bpp->pls->actx = SSH2_PKTCTX_PASSWORD;
  1620. s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
  1621. s->cur_prompt->to_server = true;
  1622. s->cur_prompt->from_server = false;
  1623. s->cur_prompt->name = dupstr("SSH password");
  1624. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  1625. s->username, s->hostname),
  1626. false);
  1627. s->spr = seat_get_userpass_input(
  1628. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1629. while (s->spr.kind == SPRK_INCOMPLETE) {
  1630. crReturnV;
  1631. s->spr = seat_get_userpass_input(
  1632. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1633. }
  1634. if (spr_is_abort(s->spr)) {
  1635. /*
  1636. * Failed to get responses. Terminate.
  1637. */
  1638. free_prompts(s->cur_prompt);
  1639. s->cur_prompt = NULL;
  1640. ssh_bpp_queue_disconnect(
  1641. s->ppl.bpp, "Unable to authenticate",
  1642. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1643. ssh_spr_close(s->ppl.ssh, s->spr, "password prompt");
  1644. return;
  1645. }
  1646. /*
  1647. * Squirrel away the password. (We may need it later if
  1648. * asked to change it.)
  1649. */
  1650. s->password = prompt_get_result(s->cur_prompt->prompts[0]);
  1651. free_prompts(s->cur_prompt);
  1652. s->cur_prompt = NULL;
  1653. /*
  1654. * Send the password packet.
  1655. *
  1656. * We pad out the password packet to 256 bytes to make
  1657. * it harder for an attacker to find the length of the
  1658. * user's password.
  1659. *
  1660. * Anyone using a password longer than 256 bytes
  1661. * probably doesn't have much to worry about from
  1662. * people who find out how long their password is!
  1663. */
  1664. s->pktout = ssh_bpp_new_pktout(
  1665. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1666. put_stringz(s->pktout, s->username);
  1667. put_stringz(s->pktout, s->successor_layer->vt->name);
  1668. put_stringz(s->pktout, "password");
  1669. put_bool(s->pktout, false);
  1670. put_stringz(s->pktout, s->password);
  1671. s->pktout->minlen = 256;
  1672. pq_push(s->ppl.out_pq, s->pktout);
  1673. ppl_logevent("Sent password");
  1674. s->type = AUTH_TYPE_PASSWORD;
  1675. /*
  1676. * Wait for next packet, in case it's a password change
  1677. * request.
  1678. */
  1679. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1680. changereq_first_time = true;
  1681. while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
  1682. /*
  1683. * We're being asked for a new password
  1684. * (perhaps not for the first time).
  1685. * Loop until the server accepts it.
  1686. */
  1687. bool got_new = false; /* not live over crReturn */
  1688. ptrlen prompt; /* not live over crReturn */
  1689. {
  1690. const char *msg;
  1691. if (changereq_first_time)
  1692. msg = "Server requested password change";
  1693. else
  1694. msg = "Server rejected new password";
  1695. ppl_logevent("%s", msg);
  1696. ppl_printf("%s\r\n", msg);
  1697. }
  1698. prompt = get_string(pktin);
  1699. s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
  1700. s->cur_prompt->to_server = true;
  1701. s->cur_prompt->from_server = false;
  1702. s->cur_prompt->name = dupstr("New SSH password");
  1703. s->cur_prompt->instruction = mkstr(prompt);
  1704. s->cur_prompt->instr_reqd = true;
  1705. /*
  1706. * There's no explicit requirement in the protocol
  1707. * for the "old" passwords in the original and
  1708. * password-change messages to be the same, and
  1709. * apparently some Cisco kit supports password change
  1710. * by the user entering a blank password originally
  1711. * and the real password subsequently, so,
  1712. * reluctantly, we prompt for the old password again.
  1713. *
  1714. * (On the other hand, some servers don't even bother
  1715. * to check this field.)
  1716. */
  1717. add_prompt(s->cur_prompt,
  1718. dupstr("Current password (blank for previously entered password): "),
  1719. false);
  1720. add_prompt(s->cur_prompt, dupstr("Enter new password: "),
  1721. false);
  1722. add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
  1723. false);
  1724. /*
  1725. * Loop until the user manages to enter the same
  1726. * password twice.
  1727. */
  1728. while (!got_new) {
  1729. s->spr = seat_get_userpass_input(
  1730. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1731. while (s->spr.kind == SPRK_INCOMPLETE) {
  1732. crReturnV;
  1733. s->spr = seat_get_userpass_input(
  1734. ppl_get_iseat(&s->ppl), s->cur_prompt);
  1735. }
  1736. if (spr_is_abort(s->spr)) {
  1737. /*
  1738. * Failed to get responses. Terminate.
  1739. */
  1740. /* burn the evidence */
  1741. free_prompts(s->cur_prompt);
  1742. s->cur_prompt = NULL;
  1743. smemclr(s->password, strlen(s->password));
  1744. sfree(s->password);
  1745. ssh_bpp_queue_disconnect(
  1746. s->ppl.bpp, "Unable to authenticate",
  1747. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1748. ssh_spr_close(s->ppl.ssh, s->spr,
  1749. "password-change prompt");
  1750. return;
  1751. }
  1752. /*
  1753. * If the user specified a new original password
  1754. * (IYSWIM), overwrite any previously specified
  1755. * one.
  1756. * (A side effect is that the user doesn't have to
  1757. * re-enter it if they louse up the new password.)
  1758. */
  1759. if (s->cur_prompt->prompts[0]->result->s[0]) {
  1760. smemclr(s->password, strlen(s->password));
  1761. /* burn the evidence */
  1762. sfree(s->password);
  1763. s->password = prompt_get_result(
  1764. s->cur_prompt->prompts[0]);
  1765. }
  1766. /*
  1767. * Check the two new passwords match.
  1768. */
  1769. got_new = !strcmp(
  1770. prompt_get_result_ref(s->cur_prompt->prompts[1]),
  1771. prompt_get_result_ref(s->cur_prompt->prompts[2]));
  1772. if (!got_new)
  1773. /* They don't. Silly user. */
  1774. ppl_printf("Passwords do not match\r\n");
  1775. }
  1776. /*
  1777. * Send the new password (along with the old one).
  1778. * (see above for padding rationale)
  1779. */
  1780. s->pktout = ssh_bpp_new_pktout(
  1781. s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  1782. put_stringz(s->pktout, s->username);
  1783. put_stringz(s->pktout, s->successor_layer->vt->name);
  1784. put_stringz(s->pktout, "password");
  1785. put_bool(s->pktout, true);
  1786. put_stringz(s->pktout, s->password);
  1787. put_stringz(s->pktout, prompt_get_result_ref(
  1788. s->cur_prompt->prompts[1]));
  1789. free_prompts(s->cur_prompt);
  1790. s->cur_prompt = NULL;
  1791. s->pktout->minlen = 256;
  1792. pq_push(s->ppl.out_pq, s->pktout);
  1793. ppl_logevent("Sent new password");
  1794. /*
  1795. * Now see what the server has to say about it.
  1796. * (If it's CHANGEREQ again, it's not happy with the
  1797. * new password.)
  1798. */
  1799. crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
  1800. changereq_first_time = false;
  1801. }
  1802. /*
  1803. * We need to reexamine the current pktin at the top
  1804. * of the loop. Either:
  1805. * - we weren't asked to change password at all, in
  1806. * which case it's a SUCCESS or FAILURE with the
  1807. * usual meaning
  1808. * - we sent a new password, and the server was
  1809. * either OK with it (SUCCESS or FAILURE w/partial
  1810. * success) or unhappy with the _old_ password
  1811. * (FAILURE w/o partial success)
  1812. * In any of these cases, we go back to the top of
  1813. * the loop and start again.
  1814. */
  1815. pq_push_front(s->ppl.in_pq, pktin);
  1816. /*
  1817. * We don't need the old password any more, in any
  1818. * case. Burn the evidence.
  1819. */
  1820. smemclr(s->password, strlen(s->password));
  1821. sfree(s->password);
  1822. } else {
  1823. ssh_bpp_queue_disconnect(
  1824. s->ppl.bpp,
  1825. "No supported authentication methods available",
  1826. SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE);
  1827. ssh_sw_abort(s->ppl.ssh, "No supported authentication methods "
  1828. "available (server sent: %s)",
  1829. s->last_methods_string->s);
  1830. return;
  1831. }
  1832. }
  1833. try_new_username:;
  1834. }
  1835. userauth_success:
  1836. if (s->notrivialauth && s->is_trivial_auth) {
  1837. ssh_proto_error(s->ppl.ssh, "Authentication was trivial! "
  1838. "Abandoning session as specified in configuration.");
  1839. return;
  1840. }
  1841. /*
  1842. * We've just received USERAUTH_SUCCESS, and we haven't sent
  1843. * any packets since. Signal the transport layer to consider
  1844. * doing an immediate rekey, if it has any reason to want to.
  1845. */
  1846. ssh2_transport_notify_auth_done(s->transport_layer);
  1847. /*
  1848. * Finally, hand over to our successor layer, and return
  1849. * immediately without reaching the crFinishV: ssh_ppl_replace
  1850. * will have freed us, so crFinishV's zeroing-out of crState would
  1851. * be a use-after-free bug.
  1852. */
  1853. {
  1854. PacketProtocolLayer *successor = s->successor_layer;
  1855. s->successor_layer = NULL; /* avoid freeing it ourself */
  1856. ssh_ppl_replace(&s->ppl, successor);
  1857. return; /* we've just freed s, so avoid even touching s->crState */
  1858. }
  1859. crFinishV;
  1860. }
  1861. static void ssh2_userauth_print_banner(struct ssh2_userauth_state *s)
  1862. {
  1863. if (bufchain_size(&s->banner) &&
  1864. (seat_verbose(s->ppl.seat) || seat_interactive(s->ppl.seat))) {
  1865. if (s->banner_scc) {
  1866. seat_antispoof_msg(
  1867. ppl_get_iseat(&s->ppl),
  1868. "Pre-authentication banner message from server:");
  1869. seat_set_trust_status(s->ppl.seat, false);
  1870. }
  1871. bool mid_line = false;
  1872. while (bufchain_size(&s->banner) > 0) {
  1873. ptrlen data = bufchain_prefix(&s->banner);
  1874. seat_banner_pl(ppl_get_iseat(&s->ppl), data);
  1875. mid_line =
  1876. (((const char *)data.ptr)[data.len-1] != '\n');
  1877. bufchain_consume(&s->banner, data.len);
  1878. }
  1879. bufchain_clear(&s->banner);
  1880. if (mid_line)
  1881. seat_banner_pl(ppl_get_iseat(&s->ppl),
  1882. PTRLEN_LITERAL("\r\n"));
  1883. if (s->banner_scc) {
  1884. seat_set_trust_status(s->ppl.seat, true);
  1885. seat_antispoof_msg(ppl_get_iseat(&s->ppl),
  1886. "End of banner message from server");
  1887. }
  1888. }
  1889. }
  1890. static bool ssh2_userauth_ki_setup_prompts(
  1891. struct ssh2_userauth_state *s, BinarySource *src, bool plugin)
  1892. {
  1893. ptrlen name, inst;
  1894. strbuf *sb;
  1895. /*
  1896. * We've got a fresh USERAUTH_INFO_REQUEST. Get the preamble and
  1897. * start building a prompt.
  1898. */
  1899. name = get_string(src);
  1900. inst = get_string(src);
  1901. get_string(src); /* skip language tag */
  1902. s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
  1903. s->cur_prompt->to_server = true;
  1904. s->cur_prompt->from_server = true;
  1905. /*
  1906. * Get any prompt(s) from the packet.
  1907. */
  1908. s->num_prompts = get_uint32(src);
  1909. for (uint32_t i = 0; i < s->num_prompts; i++) {
  1910. s->is_trivial_auth = false;
  1911. ptrlen prompt = get_string(src);
  1912. bool echo = get_bool(src);
  1913. if (get_err(src)) {
  1914. ssh_proto_error(s->ppl.ssh, "%s sent truncated %s packet",
  1915. plugin ? "Plugin" : "Server",
  1916. plugin ? "PLUGIN_KI_USER_REQUEST" :
  1917. "SSH_MSG_USERAUTH_INFO_REQUEST");
  1918. return false;
  1919. }
  1920. sb = strbuf_new();
  1921. if (!prompt.len) {
  1922. put_fmt(sb, "<%s failed to send prompt>: ",
  1923. plugin ? "plugin" : "server");
  1924. } else if (s->ki_scc) {
  1925. stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
  1926. put_datapl(s->ki_scc, prompt);
  1927. stripctrl_retarget(s->ki_scc, NULL);
  1928. } else {
  1929. put_datapl(sb, prompt);
  1930. }
  1931. add_prompt(s->cur_prompt, strbuf_to_str(sb), echo);
  1932. }
  1933. /*
  1934. * Make the header strings. This includes the 'name' (optional
  1935. * dialog-box title) and 'instruction' from the server.
  1936. *
  1937. * First, display our disambiguating header line if this is the
  1938. * first time round the loop - _unless_ the server has sent a
  1939. * completely empty k-i packet with no prompts _or_ text, which
  1940. * apparently some do. In that situation there's no need to alert
  1941. * the user that the following text is server- supplied, because,
  1942. * well, _what_ text?
  1943. *
  1944. * We also only do this if we got a stripctrl, because if we
  1945. * didn't, that suggests this is all being done via dialog boxes
  1946. * anyway.
  1947. */
  1948. if (!s->ki_printed_header && s->ki_scc &&
  1949. (s->num_prompts || name.len || inst.len)) {
  1950. seat_antispoof_msg(
  1951. ppl_get_iseat(&s->ppl),
  1952. (plugin ?
  1953. "Keyboard-interactive authentication prompts from plugin:" :
  1954. "Keyboard-interactive authentication prompts from server:"));
  1955. s->ki_printed_header = true;
  1956. seat_set_trust_status(s->ppl.seat, false);
  1957. }
  1958. sb = strbuf_new();
  1959. if (name.len) {
  1960. if (s->ki_scc) {
  1961. stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
  1962. put_datapl(s->ki_scc, name);
  1963. stripctrl_retarget(s->ki_scc, NULL);
  1964. } else {
  1965. put_datapl(sb, name);
  1966. }
  1967. s->cur_prompt->name_reqd = true;
  1968. } else {
  1969. if (plugin)
  1970. put_datapl(sb, PTRLEN_LITERAL(
  1971. "Communication with authentication plugin"));
  1972. else
  1973. put_datapl(sb, PTRLEN_LITERAL("SSH server authentication"));
  1974. s->cur_prompt->name_reqd = false;
  1975. }
  1976. s->cur_prompt->name = strbuf_to_str(sb);
  1977. sb = strbuf_new();
  1978. if (inst.len) {
  1979. if (s->ki_scc) {
  1980. stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
  1981. put_datapl(s->ki_scc, inst);
  1982. stripctrl_retarget(s->ki_scc, NULL);
  1983. } else {
  1984. put_datapl(sb, inst);
  1985. }
  1986. s->cur_prompt->instr_reqd = true;
  1987. } else {
  1988. s->cur_prompt->instr_reqd = false;
  1989. }
  1990. if (sb->len)
  1991. s->cur_prompt->instruction = strbuf_to_str(sb);
  1992. else
  1993. strbuf_free(sb);
  1994. return true;
  1995. }
  1996. static bool ssh2_userauth_ki_run_prompts(struct ssh2_userauth_state *s)
  1997. {
  1998. s->spr = seat_get_userpass_input(
  1999. ppl_get_iseat(&s->ppl), s->cur_prompt);
  2000. return s->spr.kind != SPRK_INCOMPLETE;
  2001. }
  2002. static void ssh2_userauth_ki_write_responses(
  2003. struct ssh2_userauth_state *s, BinarySink *bs)
  2004. {
  2005. put_uint32(bs, s->num_prompts);
  2006. for (uint32_t i = 0; i < s->num_prompts; i++)
  2007. put_stringz(bs, prompt_get_result_ref(s->cur_prompt->prompts[i]));
  2008. /*
  2009. * Free the prompts structure from this iteration. If there's
  2010. * another, a new one will be allocated when we return to the top
  2011. * of this while loop.
  2012. */
  2013. free_prompts(s->cur_prompt);
  2014. s->cur_prompt = NULL;
  2015. }
  2016. static void ssh2_userauth_add_session_id(
  2017. struct ssh2_userauth_state *s, strbuf *sigdata)
  2018. {
  2019. if (s->ppl.remote_bugs & BUG_SSH2_PK_SESSIONID) {
  2020. put_datapl(sigdata, s->session_id);
  2021. } else {
  2022. put_stringpl(sigdata, s->session_id);
  2023. }
  2024. }
  2025. static void ssh2_userauth_agent_query(
  2026. struct ssh2_userauth_state *s, strbuf *req)
  2027. {
  2028. void *response;
  2029. int response_len;
  2030. sfree(s->agent_response_to_free);
  2031. s->agent_response_to_free = NULL;
  2032. s->auth_agent_query = agent_query(req, &response, &response_len,
  2033. ssh2_userauth_agent_callback, s);
  2034. if (!s->auth_agent_query)
  2035. ssh2_userauth_agent_callback(s, response, response_len);
  2036. }
  2037. static void ssh2_userauth_agent_callback(void *uav, void *reply, int replylen)
  2038. {
  2039. struct ssh2_userauth_state *s = (struct ssh2_userauth_state *)uav;
  2040. s->auth_agent_query = NULL;
  2041. s->agent_response_to_free = reply;
  2042. s->agent_response = make_ptrlen(reply, replylen);
  2043. queue_idempotent_callback(&s->ppl.ic_process_queue);
  2044. }
  2045. /*
  2046. * Helper function to add the algorithm and public key strings to a
  2047. * "publickey" auth packet. Deals with overriding both strings if the
  2048. * user has provided a detached certificate which matches the public
  2049. * key in question.
  2050. */
  2051. static void ssh2_userauth_add_alg_and_publickey(
  2052. struct ssh2_userauth_state *s, PktOut *pkt, ptrlen alg, ptrlen pkblob)
  2053. {
  2054. PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
  2055. if (s->detached_cert_blob) {
  2056. ptrlen detached_cert_pl = ptrlen_from_strbuf(s->detached_cert_blob);
  2057. strbuf *certbase = NULL, *pkbase = NULL;
  2058. bool done = false;
  2059. const ssh_keyalg *pkalg = find_pubkey_alg_len(alg);
  2060. ssh_key *certkey = NULL, *pk = NULL;
  2061. strbuf *fail_reason = strbuf_new();
  2062. bool verbose = true;
  2063. /*
  2064. * Whether or not we send the certificate, we're likely to
  2065. * generate a log message about it. But we don't want to log
  2066. * once for the offer and once for the real auth attempt, so
  2067. * we de-duplicate by remembering the last public key this
  2068. * function saw. */
  2069. if (!s->cert_pubkey_diagnosed)
  2070. s->cert_pubkey_diagnosed = strbuf_new();
  2071. if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(s->cert_pubkey_diagnosed),
  2072. pkblob)) {
  2073. verbose = false;
  2074. } else {
  2075. /* Log this time, but arrange that we don't mention it next time */
  2076. strbuf_clear(s->cert_pubkey_diagnosed);
  2077. put_datapl(s->cert_pubkey_diagnosed, pkblob);
  2078. }
  2079. /*
  2080. * Check that the public key we're replacing is compatible
  2081. * with the certificate, in that they should have the same
  2082. * base public key.
  2083. */
  2084. const ssh_keyalg *certalg = pubkey_blob_to_alg(detached_cert_pl);
  2085. assert(certalg); /* we checked this before setting s->detached_blob */
  2086. assert(certalg->is_certificate); /* and this too */
  2087. certkey = ssh_key_new_pub(certalg, detached_cert_pl);
  2088. if (!certkey) {
  2089. put_fmt(fail_reason, "certificate key file is invalid");
  2090. goto no_match;
  2091. }
  2092. certbase = strbuf_new();
  2093. ssh_key_public_blob(ssh_key_base_key(certkey),
  2094. BinarySink_UPCAST(certbase));
  2095. if (ptrlen_eq_ptrlen(pkblob, ptrlen_from_strbuf(certbase)))
  2096. goto match; /* yes, a match! */
  2097. /*
  2098. * If we reach here, the certificate's base key was not
  2099. * identical to the key we're given. But it might still be
  2100. * identical to the _base_ key of the key we're given, if we
  2101. * were using a differently certified version of the same key.
  2102. * In that situation, the detached cert should still override.
  2103. */
  2104. if (!pkalg) {
  2105. put_fmt(fail_reason, "unable to identify algorithm of base key");
  2106. goto no_match;
  2107. }
  2108. pk = ssh_key_new_pub(pkalg, pkblob);
  2109. if (!pk) {
  2110. put_fmt(fail_reason, "base public key is invalid");
  2111. goto no_match;
  2112. }
  2113. pkbase = strbuf_new();
  2114. ssh_key_public_blob(ssh_key_base_key(pk), BinarySink_UPCAST(pkbase));
  2115. if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(pkbase),
  2116. ptrlen_from_strbuf(certbase)))
  2117. goto match; /* yes, a match on 2nd attempt! */
  2118. /* Give up; we've tried to match these keys up and failed. */
  2119. put_fmt(fail_reason, "base public key does not match certificate");
  2120. goto no_match;
  2121. match:
  2122. /*
  2123. * The two keys match, so insert the detached certificate into
  2124. * the output packet in place of the public key we were given.
  2125. *
  2126. * However, we need to be a bit careful with the algorithm
  2127. * name: we might need to upgrade it to one that matches the
  2128. * original algorithm name. (If we were asked to add an
  2129. * ssh-rsa key but were given algorithm name "rsa-sha2-512",
  2130. * then instead of the certificate's algorithm name
  2131. * ssh-rsa-cert-v01@... we need to write the corresponding
  2132. * SHA-512 name rsa-sha2-512-cert-v01@... .)
  2133. */
  2134. if (verbose) {
  2135. ppl_logevent("Sending public key with certificate from \"%s\"",
  2136. filename_to_str(s->detached_cert_file));
  2137. }
  2138. {
  2139. /* Strip off any existing certificate-nature from pkalg,
  2140. * for the case where we're replacing a cert embedded in
  2141. * the key with the detached one. The second argument of
  2142. * ssh_keyalg_related_alg is expected to be one of the
  2143. * bare key algorithms, or nothing useful will happen. */
  2144. const ssh_keyalg *pkalg_base =
  2145. pkalg->base_alg ? pkalg->base_alg : pkalg;
  2146. /* Construct an algorithm string that includes both the
  2147. * signature subtype (e.g. rsa-sha2-512) and the
  2148. * certificate-ness. Exception: in earlier versions of
  2149. * OpenSSH we don't want to do that, and must send just
  2150. * ssh-rsa-cert-... even when we're delivering a non-SHA-1
  2151. * signature. */
  2152. const ssh_keyalg *output_alg =
  2153. ssh_keyalg_related_alg(certalg, pkalg_base);
  2154. ptrlen output_id = ptrlen_from_asciz(output_alg->ssh_id);
  2155. output_id = workaround_rsa_sha2_cert_userauth(s, output_id);
  2156. put_stringpl(pkt, output_id);
  2157. }
  2158. put_stringpl(pkt, ptrlen_from_strbuf(s->detached_cert_blob));
  2159. done = true;
  2160. goto out;
  2161. no_match:
  2162. /* Log that we didn't send the certificate, if this public key
  2163. * isn't the same one as last call to this function. (Need to
  2164. * avoid verbosely logging once for the offer and once for the
  2165. * real auth attempt.) */
  2166. if (verbose) {
  2167. ppl_logevent("Not substituting certificate \"%s\" for public "
  2168. "key: %s", filename_to_str(s->detached_cert_file),
  2169. fail_reason->s);
  2170. if (s->publickey_blob) {
  2171. /* If the user provided a specific key file to use (i.e.
  2172. * this wasn't just a key we picked opportunistically out
  2173. * of an agent), then they probably _care_ that we didn't
  2174. * send the certificate, so we should make a loud error
  2175. * message about it as well as just commenting in the
  2176. * Event Log. */
  2177. ppl_printf("Unable to use certificate \"%s\" with public "
  2178. "key \"%s\": %s\r\n",
  2179. filename_to_str(s->detached_cert_file),
  2180. filename_to_str(s->keyfile),
  2181. fail_reason->s);
  2182. }
  2183. }
  2184. out:
  2185. /* Whether we did that or not, free our stuff. */
  2186. if (certbase)
  2187. strbuf_free(certbase);
  2188. if (pkbase)
  2189. strbuf_free(pkbase);
  2190. if (certkey)
  2191. ssh_key_free(certkey);
  2192. if (pk)
  2193. ssh_key_free(pk);
  2194. strbuf_free(fail_reason);
  2195. /* And if we did, don't fall through to the alternative below */
  2196. if (done)
  2197. return;
  2198. }
  2199. /* In all other cases, basically just put in what we were given -
  2200. * except for the same bug workaround as above. */
  2201. alg = workaround_rsa_sha2_cert_userauth(s, alg);
  2202. put_stringpl(pkt, alg);
  2203. put_stringpl(pkt, pkblob);
  2204. }
  2205. static ptrlen workaround_rsa_sha2_cert_userauth(
  2206. struct ssh2_userauth_state *s, ptrlen id)
  2207. {
  2208. if (!(s->ppl.remote_bugs & BUG_RSA_SHA2_CERT_USERAUTH))
  2209. return id;
  2210. /*
  2211. * No need to try to do this in a general way based on the
  2212. * relations between ssh_keyalgs; we know there are a limited
  2213. * number of affected versions of OpenSSH, so this doesn't have to
  2214. * be futureproof against later additions to the family.
  2215. */
  2216. if (ptrlen_eq_string(id, "[email protected]") ||
  2217. ptrlen_eq_string(id, "[email protected]"))
  2218. return PTRLEN_LITERAL("[email protected]");
  2219. return id;
  2220. }
  2221. /*
  2222. * Helper function to add an SSH-2 signature blob to a packet. Expects
  2223. * to be shown the public key blob as well as the signature blob.
  2224. * Normally just appends the sig blob unmodified as a string, except
  2225. * that it optionally breaks it open and fiddle with it to work around
  2226. * BUG_SSH2_RSA_PADDING.
  2227. */
  2228. static void ssh2_userauth_add_sigblob(
  2229. struct ssh2_userauth_state *s, PktOut *pkt, ptrlen pkblob, ptrlen sigblob)
  2230. {
  2231. BinarySource pk[1], sig[1];
  2232. BinarySource_BARE_INIT_PL(pk, pkblob);
  2233. BinarySource_BARE_INIT_PL(sig, sigblob);
  2234. /* dmemdump(pkblob, pkblob_len); */
  2235. /* dmemdump(sigblob, sigblob_len); */
  2236. /*
  2237. * See if this is in fact an ssh-rsa signature and a buggy
  2238. * server; otherwise we can just do this the easy way.
  2239. */
  2240. if ((s->ppl.remote_bugs & BUG_SSH2_RSA_PADDING) &&
  2241. ptrlen_eq_string(get_string(pk), "ssh-rsa") &&
  2242. ptrlen_eq_string(get_string(sig), "ssh-rsa")) {
  2243. ptrlen mod_mp, sig_mp;
  2244. size_t sig_prefix_len;
  2245. /*
  2246. * Find the modulus and signature integers.
  2247. */
  2248. get_string(pk); /* skip over exponent */
  2249. mod_mp = get_string(pk); /* remember modulus */
  2250. sig_prefix_len = sig->pos;
  2251. sig_mp = get_string(sig);
  2252. if (get_err(pk) || get_err(sig))
  2253. goto give_up;
  2254. /*
  2255. * Find the byte length of the modulus, not counting leading
  2256. * zeroes.
  2257. */
  2258. while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) {
  2259. mod_mp.len--;
  2260. mod_mp.ptr = (const char *)mod_mp.ptr + 1;
  2261. }
  2262. /* debug("modulus length is %d\n", len); */
  2263. /* debug("signature length is %d\n", siglen); */
  2264. if (mod_mp.len > sig_mp.len) {
  2265. strbuf *substr = strbuf_new();
  2266. put_data(substr, sigblob.ptr, sig_prefix_len);
  2267. put_uint32(substr, mod_mp.len);
  2268. put_padding(substr, mod_mp.len - sig_mp.len, 0);
  2269. put_datapl(substr, sig_mp);
  2270. put_stringsb(pkt, substr);
  2271. return;
  2272. }
  2273. /* Otherwise fall through and do it the easy way. We also come
  2274. * here as a fallback if we discover above that the key blob
  2275. * is misformatted in some way. */
  2276. give_up:;
  2277. }
  2278. put_stringpl(pkt, sigblob);
  2279. }
  2280. #ifndef NO_GSSAPI
  2281. static PktOut *ssh2_userauth_gss_packet(
  2282. struct ssh2_userauth_state *s, const char *authtype)
  2283. {
  2284. strbuf *sb;
  2285. PktOut *p;
  2286. Ssh_gss_buf buf;
  2287. Ssh_gss_buf mic;
  2288. /*
  2289. * The mic is computed over the session id + intended
  2290. * USERAUTH_REQUEST packet.
  2291. */
  2292. sb = strbuf_new();
  2293. put_stringpl(sb, s->session_id);
  2294. put_byte(sb, SSH2_MSG_USERAUTH_REQUEST);
  2295. put_stringz(sb, s->username);
  2296. put_stringz(sb, s->successor_layer->vt->name);
  2297. put_stringz(sb, authtype);
  2298. /* Compute the mic */
  2299. buf.value = sb->s;
  2300. buf.length = sb->len;
  2301. s->shgss->lib->get_mic(s->shgss->lib, s->shgss->ctx, &buf, &mic);
  2302. strbuf_free(sb);
  2303. /* Now we can build the real packet */
  2304. if (strcmp(authtype, "gssapi-with-mic") == 0) {
  2305. p = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_GSSAPI_MIC);
  2306. } else {
  2307. p = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
  2308. put_stringz(p, s->username);
  2309. put_stringz(p, s->successor_layer->vt->name);
  2310. put_stringz(p, authtype);
  2311. }
  2312. put_string(p, mic.value, mic.length);
  2313. return p;
  2314. }
  2315. #endif
  2316. static bool ssh2_userauth_get_specials(
  2317. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
  2318. {
  2319. /* No specials provided by this layer. */
  2320. return false;
  2321. }
  2322. static void ssh2_userauth_special_cmd(PacketProtocolLayer *ppl,
  2323. SessionSpecialCode code, int arg)
  2324. {
  2325. /* No specials provided by this layer. */
  2326. }
  2327. static void ssh2_userauth_reconfigure(PacketProtocolLayer *ppl, Conf *conf)
  2328. {
  2329. struct ssh2_userauth_state *s =
  2330. container_of(ppl, struct ssh2_userauth_state, ppl);
  2331. ssh_ppl_reconfigure(s->successor_layer, conf);
  2332. }
  2333. static void ssh2_userauth_final_output(PacketProtocolLayer *ppl)
  2334. {
  2335. struct ssh2_userauth_state *s =
  2336. container_of(ppl, struct ssh2_userauth_state, ppl);
  2337. /*
  2338. * Check for any unconsumed banner packets that might have landed
  2339. * in our queue just before the server closed the connection, and
  2340. * add them to our banner buffer.
  2341. */
  2342. for (PktIn *pktin = pq_first(s->ppl.in_pq); pktin != NULL;
  2343. pktin = pq_next(s->ppl.in_pq, pktin)) {
  2344. if (pktin->type == SSH2_MSG_USERAUTH_BANNER)
  2345. ssh2_userauth_handle_banner_packet(s, pktin);
  2346. }
  2347. /* And now make sure we've shown the banner, before exiting */
  2348. ssh2_userauth_print_banner(s);
  2349. }