userauth2-client.c 104 KB

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