userauth2-client.c 106 KB

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