pageant.c 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692
  1. /*
  2. * pageant.c: cross-platform code to implement Pageant.
  3. */
  4. #include <stddef.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include "putty.h"
  8. #include "mpint.h"
  9. #include "ssh.h"
  10. #include "sshcr.h"
  11. #include "pageant.h"
  12. /*
  13. * We need this to link with the RSA code, because rsa_ssh1_encrypt()
  14. * pads its data with random bytes. Since we only use rsa_ssh1_decrypt()
  15. * and the signing functions, which are deterministic, this should
  16. * never be called.
  17. *
  18. * If it _is_ called, there is a _serious_ problem, because it
  19. * won't generate true random numbers. So we must scream, panic,
  20. * and exit immediately if that should happen.
  21. */
  22. void random_read(void *buf, size_t size)
  23. {
  24. modalfatalbox("Internal error: attempt to use random numbers in Pageant");
  25. }
  26. static bool pageant_local = false;
  27. struct PageantClientDialogId {
  28. int dummy;
  29. };
  30. typedef struct PageantPrivateKeySort PageantPrivateKeySort;
  31. typedef struct PageantPublicKeySort PageantPublicKeySort;
  32. typedef struct PageantPrivateKey PageantPrivateKey;
  33. typedef struct PageantPublicKey PageantPublicKey;
  34. typedef struct PageantAsyncOp PageantAsyncOp;
  35. typedef struct PageantAsyncOpVtable PageantAsyncOpVtable;
  36. typedef struct PageantClientRequestNode PageantClientRequestNode;
  37. typedef struct PageantKeyRequestNode PageantKeyRequestNode;
  38. struct PageantClientRequestNode {
  39. PageantClientRequestNode *prev, *next;
  40. };
  41. struct PageantKeyRequestNode {
  42. PageantKeyRequestNode *prev, *next;
  43. };
  44. struct PageantClientInfo {
  45. PageantClient *pc; /* goes to NULL when client is unregistered */
  46. PageantClientRequestNode head;
  47. };
  48. struct PageantAsyncOp {
  49. const PageantAsyncOpVtable *vt;
  50. PageantClientInfo *info;
  51. PageantClientRequestNode cr;
  52. PageantClientRequestId *reqid;
  53. };
  54. struct PageantAsyncOpVtable {
  55. void (*coroutine)(PageantAsyncOp *pao);
  56. void (*free)(PageantAsyncOp *pao);
  57. };
  58. static inline void pageant_async_op_coroutine(PageantAsyncOp *pao)
  59. { pao->vt->coroutine(pao); }
  60. static inline void pageant_async_op_free(PageantAsyncOp *pao)
  61. {
  62. delete_callbacks_for_context(pao);
  63. pao->vt->free(pao);
  64. }
  65. static inline void pageant_async_op_unlink(PageantAsyncOp *pao)
  66. {
  67. pao->cr.prev->next = pao->cr.next;
  68. pao->cr.next->prev = pao->cr.prev;
  69. }
  70. static inline void pageant_async_op_unlink_and_free(PageantAsyncOp *pao)
  71. {
  72. pageant_async_op_unlink(pao);
  73. pageant_async_op_free(pao);
  74. }
  75. static void pageant_async_op_callback(void *vctx)
  76. {
  77. pageant_async_op_coroutine((PageantAsyncOp *)vctx);
  78. }
  79. /*
  80. * Master lists of all the keys we have stored, in any form at all.
  81. *
  82. * We store private and public keys in separate lists, because
  83. * multiple public keys can share the same private key (due to one
  84. * having a certificate and the other not, or having more than one
  85. * different certificate). And when we decrypt or re-encrypt a private
  86. * key, we don't really want to faff about doing it multiple times if
  87. * there's more than one public key it goes with. If someone tries to
  88. * re-encrypt a key to make their machine safer against unattended
  89. * access, then it would be embarrassing to find they'd forgotten to
  90. * re-encrypt the _other_ copy of it; conversely, once you've
  91. * decrypted a key, it's pointless to make someone type yet another
  92. * passphrase.
  93. *
  94. * (Causing multiple keys to become decrypted in one go isn't a
  95. * security hole in its own right, because the signatures generated by
  96. * certified and uncertified keys are identical. So an attacker
  97. * gaining access to an agent containing one encrypted and one
  98. * cleartext key with the same private half would still be *able* to
  99. * generate signatures that went with the encrypted one, even if the
  100. * agent refused to hand them out in response to the most obvious kind
  101. * of request.)
  102. */
  103. struct PageantPrivateKeySort {
  104. /*
  105. * Information used by the sorting criterion for the private key
  106. * tree.
  107. */
  108. int ssh_version; /* 1 or 2; primary sort key */
  109. ptrlen base_pub; /* secondary sort key; never includes a certificate */
  110. };
  111. static int privkey_cmpfn(void *av, void *bv)
  112. {
  113. PageantPrivateKeySort *a = (PageantPrivateKeySort *)av;
  114. PageantPrivateKeySort *b = (PageantPrivateKeySort *)bv;
  115. if (a->ssh_version != b->ssh_version)
  116. return a->ssh_version < b->ssh_version ? -1 : +1;
  117. else
  118. return ptrlen_strcmp(a->base_pub, b->base_pub);
  119. }
  120. struct PageantPublicKeySort {
  121. /*
  122. * Information used by the sorting criterion for the public key
  123. * tree. Begins with the private key sorting criterion, so that
  124. * all the public keys sharing a private key appear adjacent in
  125. * the tree. That's a reasonably sensible order to list them in
  126. * for the user, and more importantly, it makes it easy to
  127. * discover when we're deleting the last public key that goes with
  128. * a particular private one, so as to delete that too. Easier than
  129. * messing about with fragile reference counts.
  130. */
  131. PageantPrivateKeySort priv;
  132. ptrlen full_pub; /* may match priv.base_pub, or may include a cert */
  133. };
  134. static int pubkey_cmpfn(void *av, void *bv)
  135. {
  136. PageantPublicKeySort *a = (PageantPublicKeySort *)av;
  137. PageantPublicKeySort *b = (PageantPublicKeySort *)bv;
  138. int c = privkey_cmpfn(&a->priv, &b->priv);
  139. if (c)
  140. return c;
  141. else
  142. return ptrlen_strcmp(a->full_pub, b->full_pub);
  143. }
  144. struct PageantPrivateKey {
  145. PageantPrivateKeySort sort;
  146. strbuf *base_pub; /* the true owner of sort.base_pub */
  147. union {
  148. RSAKey *rkey; /* if sort.priv.ssh_version == 1 */
  149. ssh_key *skey; /* if sort.priv.ssh_version == 2 */
  150. };
  151. strbuf *encrypted_key_file;
  152. /* encrypted_key_comment stores the comment belonging to the
  153. * encrypted key file. This is used when presenting deferred
  154. * decryption prompts, because if the user had encrypted their
  155. * uncert and cert keys with different passphrases, the passphrase
  156. * prompt must reliably signal which file they're supposed to be
  157. * entering the passphrase for. */
  158. char *encrypted_key_comment;
  159. bool decryption_prompt_active;
  160. PageantKeyRequestNode blocked_requests;
  161. PageantClientDialogId dlgid;
  162. };
  163. static tree234 *privkeytree;
  164. struct PageantPublicKey {
  165. PageantPublicKeySort sort;
  166. strbuf *base_pub; /* the true owner of sort.priv.base_pub */
  167. strbuf *full_pub; /* the true owner of sort.full_pub */
  168. char *comment;
  169. };
  170. static tree234 *pubkeytree;
  171. typedef struct PageantSignOp PageantSignOp;
  172. struct PageantSignOp {
  173. PageantPrivateKey *priv;
  174. strbuf *data_to_sign;
  175. unsigned flags;
  176. int crLine;
  177. unsigned char failure_type;
  178. PageantKeyRequestNode pkr;
  179. PageantAsyncOp pao;
  180. };
  181. /* Master lock that indicates whether a GUI request is currently in
  182. * progress */
  183. static bool gui_request_in_progress = false;
  184. static PageantKeyRequestNode requests_blocked_on_gui =
  185. { &requests_blocked_on_gui, &requests_blocked_on_gui };
  186. static void failure(PageantClient *pc, PageantClientRequestId *reqid,
  187. strbuf *sb, unsigned char type, const char *fmt, ...);
  188. static void fail_requests_for_key(PageantPrivateKey *priv, const char *reason);
  189. static PageantPublicKey *pageant_nth_pubkey(int ssh_version, int i);
  190. static void pk_priv_free(PageantPrivateKey *priv)
  191. {
  192. if (priv->base_pub)
  193. strbuf_free(priv->base_pub);
  194. if (priv->sort.ssh_version == 1 && priv->rkey) {
  195. freersakey(priv->rkey);
  196. sfree(priv->rkey);
  197. }
  198. if (priv->sort.ssh_version == 2 && priv->skey) {
  199. ssh_key_free(priv->skey);
  200. }
  201. if (priv->encrypted_key_file)
  202. strbuf_free(priv->encrypted_key_file);
  203. if (priv->encrypted_key_comment)
  204. sfree(priv->encrypted_key_comment);
  205. fail_requests_for_key(priv, "key deleted from Pageant while signing "
  206. "request was pending");
  207. sfree(priv);
  208. }
  209. static void pk_pub_free(PageantPublicKey *pub)
  210. {
  211. if (pub->full_pub)
  212. strbuf_free(pub->full_pub);
  213. sfree(pub->comment);
  214. sfree(pub);
  215. }
  216. static strbuf *makeblob1(RSAKey *rkey)
  217. {
  218. strbuf *blob = strbuf_new();
  219. rsa_ssh1_public_blob(BinarySink_UPCAST(blob), rkey,
  220. RSA_SSH1_EXPONENT_FIRST);
  221. return blob;
  222. }
  223. static strbuf *makeblob2full(ssh_key *key)
  224. {
  225. strbuf *blob = strbuf_new();
  226. ssh_key_public_blob(key, BinarySink_UPCAST(blob));
  227. return blob;
  228. }
  229. static strbuf *makeblob2base(ssh_key *key)
  230. {
  231. strbuf *blob = strbuf_new();
  232. ssh_key_public_blob(ssh_key_base_key(key), BinarySink_UPCAST(blob));
  233. return blob;
  234. }
  235. static PageantPrivateKey *pub_to_priv(PageantPublicKey *pub)
  236. {
  237. PageantPrivateKey *priv = find234(privkeytree, &pub->sort.priv, NULL);
  238. assert(priv && "Public and private trees out of sync!");
  239. return priv;
  240. }
  241. static PageantPublicKey *findpubkey1(RSAKey *reqkey)
  242. {
  243. strbuf *blob = makeblob1(reqkey);
  244. PageantPublicKeySort sort;
  245. sort.priv.ssh_version = 1;
  246. sort.priv.base_pub = ptrlen_from_strbuf(blob);
  247. sort.full_pub = ptrlen_from_strbuf(blob);
  248. PageantPublicKey *toret = find234(pubkeytree, &sort, NULL);
  249. strbuf_free(blob);
  250. return toret;
  251. }
  252. /*
  253. * Constructs the base_pub element of a PageantPublicKeySort, starting
  254. * from full_pub. This may involve allocating a strbuf to store it in,
  255. * which must survive until after you've finished using the resulting
  256. * PageantPublicKeySort. Hence, the strbuf (if any) is returned from
  257. * this function, and if it's non-NULL then the caller must eventually
  258. * free it.
  259. */
  260. static strbuf *make_base_pub_2(PageantPublicKeySort *sort)
  261. {
  262. /* Start with the fallback option of making base_pub equal full_pub */
  263. sort->priv.base_pub = sort->full_pub;
  264. /* Now reconstruct a distinct base_pub without a cert, if possible
  265. * and necessary */
  266. strbuf *base_pub = NULL;
  267. BinarySource src[1];
  268. BinarySource_BARE_INIT_PL(src, sort->full_pub);
  269. ptrlen algname = get_string(src);
  270. const ssh_keyalg *alg = find_pubkey_alg_len(algname);
  271. if (alg && alg->is_certificate) {
  272. ssh_key *key = ssh_key_new_pub(alg, sort->full_pub);
  273. if (key) {
  274. base_pub = strbuf_new();
  275. ssh_key_public_blob(ssh_key_base_key(key),
  276. BinarySink_UPCAST(base_pub));
  277. sort->priv.base_pub = ptrlen_from_strbuf(base_pub);
  278. ssh_key_free(key);
  279. }
  280. }
  281. return base_pub; /* caller must free once they're done with sort */
  282. }
  283. static PageantPublicKey *findpubkey2(ptrlen full_pub)
  284. {
  285. PageantPublicKeySort sort;
  286. sort.priv.ssh_version = 2;
  287. sort.full_pub = full_pub;
  288. strbuf *base_pub = make_base_pub_2(&sort);
  289. PageantPublicKey *toret = find234(pubkeytree, &sort, NULL);
  290. if (base_pub)
  291. strbuf_free(base_pub);
  292. return toret;
  293. }
  294. static int find_first_pubkey_for_version(int ssh_version)
  295. {
  296. PageantPublicKeySort sort;
  297. sort.priv.ssh_version = ssh_version;
  298. sort.priv.base_pub = PTRLEN_LITERAL("");
  299. sort.full_pub = PTRLEN_LITERAL("");
  300. int pos;
  301. if (findrelpos234(pubkeytree, &sort, NULL, REL234_GE, &pos))
  302. return pos;
  303. return count234(pubkeytree);
  304. }
  305. static int count_keys(int ssh_version)
  306. {
  307. return (find_first_pubkey_for_version(ssh_version + 1) -
  308. find_first_pubkey_for_version(ssh_version));
  309. }
  310. int pageant_count_ssh1_keys(void) { return count_keys(1); }
  311. int pageant_count_ssh2_keys(void) { return count_keys(2); }
  312. /*
  313. * Common code to add a key to the trees. We fill in as many fields
  314. * here as we can share between SSH versions: the ptrlens in the
  315. * sorting field, the whole of pub->sort.priv, and the linked list of
  316. * blocked requests.
  317. */
  318. static bool pageant_add_key_common(PageantPublicKey *pub,
  319. PageantPrivateKey *priv)
  320. {
  321. int ssh_version = priv->sort.ssh_version;
  322. priv->sort.base_pub = ptrlen_from_strbuf(priv->base_pub);
  323. pub->base_pub = strbuf_dup(priv->sort.base_pub);
  324. pub->sort.priv.ssh_version = priv->sort.ssh_version;
  325. pub->sort.priv.base_pub = ptrlen_from_strbuf(pub->base_pub);
  326. pub->sort.full_pub = ptrlen_from_strbuf(pub->full_pub);
  327. priv->blocked_requests.next = priv->blocked_requests.prev =
  328. &priv->blocked_requests;
  329. /*
  330. * Try to add the private key to privkeytree, or combine new parts
  331. * of it with what's already there.
  332. */
  333. PageantPrivateKey *priv_in_tree = add234(privkeytree, priv);
  334. if (priv_in_tree == priv) {
  335. /* The key wasn't in the tree at all, and we've just added it. */
  336. } else {
  337. /* The key was already in the tree, so we'll be freeing priv. */
  338. if (ssh_version == 2 && priv->skey && !priv_in_tree->skey) {
  339. /* The key was only stored encrypted, and now we have an
  340. * unencrypted version to add to the existing record. */
  341. priv_in_tree->skey = priv->skey;
  342. priv->skey = NULL; /* so pk_priv_free won't free it */
  343. }
  344. if (ssh_version == 2 && priv->encrypted_key_file &&
  345. !priv_in_tree->encrypted_key_file) {
  346. /* Conversely, the key was only stored in clear, and now
  347. * we have an encrypted version to add to it. */
  348. priv_in_tree->encrypted_key_file = priv->encrypted_key_file;
  349. priv->encrypted_key_file = NULL;
  350. priv_in_tree->encrypted_key_comment = priv->encrypted_key_comment;
  351. priv->encrypted_key_comment = NULL;
  352. }
  353. pk_priv_free(priv);
  354. }
  355. /*
  356. * Try to add the public key.
  357. */
  358. PageantPublicKey *pub_in_tree = add234(pubkeytree, pub);
  359. if (pub_in_tree == pub) {
  360. /* Successfully added a new key. */
  361. return true;
  362. } else {
  363. /* This public key was already there. */
  364. pk_pub_free(pub);
  365. return false;
  366. }
  367. }
  368. static bool pageant_add_ssh1_key(RSAKey *rkey)
  369. {
  370. PageantPublicKey *pub = snew(PageantPublicKey);
  371. memset(pub, 0, sizeof(PageantPublicKey));
  372. PageantPrivateKey *priv = snew(PageantPrivateKey);
  373. memset(priv, 0, sizeof(PageantPrivateKey));
  374. priv->sort.ssh_version = 1;
  375. priv->base_pub = makeblob1(rkey);
  376. pub->full_pub = makeblob1(rkey);
  377. if (rkey->comment)
  378. pub->comment = dupstr(rkey->comment);
  379. priv->rkey = snew(RSAKey);
  380. duprsakey(priv->rkey, rkey);
  381. return pageant_add_key_common(pub, priv);
  382. }
  383. static bool pageant_add_ssh2_key(ssh2_userkey *skey)
  384. {
  385. PageantPublicKey *pub = snew(PageantPublicKey);
  386. memset(pub, 0, sizeof(PageantPublicKey));
  387. PageantPrivateKey *priv = snew(PageantPrivateKey);
  388. memset(priv, 0, sizeof(PageantPrivateKey));
  389. priv->sort.ssh_version = 2;
  390. priv->base_pub = makeblob2base(skey->key);
  391. pub->full_pub = makeblob2full(skey->key);
  392. if (skey->comment)
  393. pub->comment = dupstr(skey->comment);
  394. /* Duplicate the ssh_key to go in priv */
  395. {
  396. strbuf *tmp = strbuf_new_nm();
  397. ssh_key_openssh_blob(skey->key, BinarySink_UPCAST(tmp));
  398. BinarySource src[1];
  399. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(tmp));
  400. priv->skey = ssh_key_new_priv_openssh(ssh_key_alg(skey->key), src);
  401. strbuf_free(tmp);
  402. }
  403. return pageant_add_key_common(pub, priv);
  404. }
  405. static bool pageant_add_ssh2_key_encrypted(PageantPublicKeySort sort,
  406. const char *comment, ptrlen keyfile)
  407. {
  408. PageantPublicKey *pub = snew(PageantPublicKey);
  409. memset(pub, 0, sizeof(PageantPublicKey));
  410. PageantPrivateKey *priv = snew(PageantPrivateKey);
  411. memset(priv, 0, sizeof(PageantPrivateKey));
  412. assert(sort.priv.ssh_version == 2);
  413. priv->sort.ssh_version = sort.priv.ssh_version;
  414. priv->base_pub = strbuf_dup(sort.priv.base_pub);
  415. pub->full_pub = strbuf_dup(sort.full_pub);
  416. pub->comment = dupstr(comment);
  417. priv->encrypted_key_file = strbuf_dup_nm(keyfile);
  418. priv->encrypted_key_comment = dupstr(comment);
  419. return pageant_add_key_common(pub, priv);
  420. }
  421. static void remove_pubkey_cleanup(PageantPublicKey *pub)
  422. {
  423. /* Common function called when we've just removed a public key
  424. * from pubkeytree: we must also check whether that was the last
  425. * public key sharing a private half, and if so, remove the
  426. * corresponding private entry too. */
  427. PageantPublicKeySort pubsearch;
  428. pubsearch.priv = pub->sort.priv;
  429. pubsearch.full_pub = PTRLEN_LITERAL("");
  430. PageantPublicKey *pubfound = findrel234(
  431. pubkeytree, &pubsearch, NULL, REL234_GE);
  432. if (pubfound && !privkey_cmpfn(&pub->sort.priv, &pubfound->sort.priv)) {
  433. /* There's still a public key which has the same sort.priv as
  434. * the one we've just removed. We're good. */
  435. } else {
  436. /* We've just removed the last public key of the family, so
  437. * delete the private half as well. */
  438. PageantPrivateKey *priv = del234(privkeytree, &pub->sort.priv);
  439. assert(priv);
  440. assert(!privkey_cmpfn(&priv->sort, &pub->sort.priv));
  441. pk_priv_free(priv);
  442. }
  443. }
  444. static PageantPublicKey *del_pubkey_pos(int pos)
  445. {
  446. PageantPublicKey *deleted = delpos234(pubkeytree, pos);
  447. remove_pubkey_cleanup(deleted);
  448. return deleted;
  449. }
  450. static void del_pubkey(PageantPublicKey *to_delete)
  451. {
  452. PageantPublicKey *deleted = del234(pubkeytree, to_delete);
  453. remove_pubkey_cleanup(deleted);
  454. }
  455. static void remove_all_keys(int ssh_version)
  456. {
  457. int start = find_first_pubkey_for_version(ssh_version);
  458. int end = find_first_pubkey_for_version(ssh_version + 1);
  459. while (end > start) {
  460. PageantPublicKey *pub = del_pubkey_pos(--end);
  461. assert(pub->sort.priv.ssh_version == ssh_version);
  462. pk_pub_free(pub);
  463. }
  464. }
  465. static void list_keys(BinarySink *bs, int ssh_version, bool extended)
  466. {
  467. int i;
  468. PageantPublicKey *pub;
  469. put_uint32(bs, count_keys(ssh_version));
  470. for (i = find_first_pubkey_for_version(ssh_version);
  471. NULL != (pub = index234(pubkeytree, i)); i++) {
  472. if (pub->sort.priv.ssh_version != ssh_version)
  473. break;
  474. if (ssh_version > 1)
  475. put_stringpl(bs, pub->sort.full_pub);
  476. else
  477. put_datapl(bs, pub->sort.full_pub); /* no header */
  478. put_stringpl(bs, ptrlen_from_asciz(pub->comment));
  479. if (extended) {
  480. assert(ssh_version == 2); /* extended lists not supported in v1 */
  481. /*
  482. * Append to each key entry a string containing extension
  483. * data. This string begins with a flags word, and may in
  484. * future contain further data if flag bits are set saying
  485. * that it does. Hence, it's wrapped in a containing
  486. * string, so that clients that only partially understand
  487. * it can still find the parts they do understand.
  488. */
  489. PageantPrivateKey *priv = pub_to_priv(pub);
  490. strbuf *sb = strbuf_new();
  491. uint32_t flags = 0;
  492. if (!priv->skey)
  493. flags |= LIST_EXTENDED_FLAG_HAS_NO_CLEARTEXT_KEY;
  494. if (priv->encrypted_key_file)
  495. flags |= LIST_EXTENDED_FLAG_HAS_ENCRYPTED_KEY_FILE;
  496. put_uint32(sb, flags);
  497. put_stringsb(bs, sb);
  498. }
  499. }
  500. }
  501. void pageant_make_keylist1(BinarySink *bs) { list_keys(bs, 1, false); }
  502. void pageant_make_keylist2(BinarySink *bs) { list_keys(bs, 2, false); }
  503. void pageant_make_keylist_extended(BinarySink *bs) { list_keys(bs, 2, true); }
  504. void pageant_register_client(PageantClient *pc)
  505. {
  506. pc->info = snew(PageantClientInfo);
  507. pc->info->pc = pc;
  508. pc->info->head.prev = pc->info->head.next = &pc->info->head;
  509. }
  510. void pageant_unregister_client(PageantClient *pc)
  511. {
  512. PageantClientInfo *info = pc->info;
  513. assert(info);
  514. assert(info->pc == pc);
  515. while (pc->info->head.next != &pc->info->head) {
  516. PageantAsyncOp *pao = container_of(pc->info->head.next,
  517. PageantAsyncOp, cr);
  518. pageant_async_op_unlink_and_free(pao);
  519. }
  520. sfree(pc->info);
  521. }
  522. static PRINTF_LIKE(5, 6) void failure(
  523. PageantClient *pc, PageantClientRequestId *reqid, strbuf *sb,
  524. unsigned char type, const char *fmt, ...)
  525. {
  526. strbuf_clear(sb);
  527. put_byte(sb, type);
  528. if (!pc->suppress_logging) {
  529. va_list ap;
  530. va_start(ap, fmt);
  531. char *msg = dupvprintf(fmt, ap);
  532. va_end(ap);
  533. pageant_client_log(pc, reqid, "reply: SSH_AGENT_FAILURE (%s)", msg);
  534. sfree(msg);
  535. }
  536. }
  537. static void signop_link_to_key(PageantSignOp *so)
  538. {
  539. assert(!so->pkr.prev);
  540. assert(!so->pkr.next);
  541. so->pkr.prev = so->priv->blocked_requests.prev;
  542. so->pkr.next = &so->priv->blocked_requests;
  543. so->pkr.prev->next = &so->pkr;
  544. so->pkr.next->prev = &so->pkr;
  545. }
  546. static void signop_link_to_pending_gui_request(PageantSignOp *so)
  547. {
  548. assert(!so->pkr.prev);
  549. assert(!so->pkr.next);
  550. so->pkr.prev = requests_blocked_on_gui.prev;
  551. so->pkr.next = &requests_blocked_on_gui;
  552. so->pkr.prev->next = &so->pkr;
  553. so->pkr.next->prev = &so->pkr;
  554. }
  555. static void signop_unlink(PageantSignOp *so)
  556. {
  557. if (so->pkr.next) {
  558. assert(so->pkr.prev);
  559. so->pkr.next->prev = so->pkr.prev;
  560. so->pkr.prev->next = so->pkr.next;
  561. so->pkr.prev = so->pkr.next = NULL;
  562. } else {
  563. assert(!so->pkr.prev);
  564. }
  565. }
  566. static void signop_free(PageantAsyncOp *pao)
  567. {
  568. PageantSignOp *so = container_of(pao, PageantSignOp, pao);
  569. strbuf_free(so->data_to_sign);
  570. sfree(so);
  571. }
  572. static bool request_passphrase(PageantClient *pc, PageantPrivateKey *priv)
  573. {
  574. if (!priv->decryption_prompt_active) {
  575. assert(!gui_request_in_progress);
  576. bool created_dlg = pageant_client_ask_passphrase(
  577. pc, &priv->dlgid, priv->encrypted_key_comment);
  578. if (!created_dlg)
  579. return false;
  580. gui_request_in_progress = true;
  581. priv->decryption_prompt_active = true;
  582. }
  583. return true;
  584. }
  585. static void signop_coroutine(PageantAsyncOp *pao)
  586. {
  587. PageantSignOp *so = container_of(pao, PageantSignOp, pao);
  588. strbuf *response;
  589. crBegin(so->crLine);
  590. while (!so->priv->skey && gui_request_in_progress) {
  591. signop_link_to_pending_gui_request(so);
  592. crReturnV;
  593. signop_unlink(so);
  594. }
  595. if (!so->priv->skey) {
  596. assert(so->priv->encrypted_key_file);
  597. if (!request_passphrase(so->pao.info->pc, so->priv)) {
  598. response = strbuf_new();
  599. failure(so->pao.info->pc, so->pao.reqid, response,
  600. so->failure_type, "on-demand decryption could not "
  601. "prompt for a passphrase");
  602. goto respond;
  603. }
  604. signop_link_to_key(so);
  605. crReturnV;
  606. signop_unlink(so);
  607. }
  608. uint32_t supported_flags = ssh_key_supported_flags(so->priv->skey);
  609. if (so->flags & ~supported_flags) {
  610. /*
  611. * We MUST reject any message containing flags we don't
  612. * understand.
  613. */
  614. response = strbuf_new();
  615. failure(so->pao.info->pc, so->pao.reqid, response, so->failure_type,
  616. "unsupported flag bits 0x%08"PRIx32,
  617. so->flags & ~supported_flags);
  618. goto respond;
  619. }
  620. char *invalid = ssh_key_invalid(so->priv->skey, so->flags);
  621. if (invalid) {
  622. response = strbuf_new();
  623. failure(so->pao.info->pc, so->pao.reqid, response, so->failure_type,
  624. "key invalid: %s", invalid);
  625. sfree(invalid);
  626. goto respond;
  627. }
  628. strbuf *signature = strbuf_new();
  629. ssh_key_sign(so->priv->skey, ptrlen_from_strbuf(so->data_to_sign),
  630. so->flags, BinarySink_UPCAST(signature));
  631. response = strbuf_new();
  632. put_byte(response, SSH2_AGENT_SIGN_RESPONSE);
  633. put_stringsb(response, signature);
  634. respond:
  635. pageant_client_got_response(so->pao.info->pc, so->pao.reqid,
  636. ptrlen_from_strbuf(response));
  637. strbuf_free(response);
  638. pageant_async_op_unlink_and_free(&so->pao);
  639. crFinishFreedV;
  640. }
  641. static const PageantAsyncOpVtable signop_vtable = {
  642. .coroutine = signop_coroutine,
  643. .free = signop_free,
  644. };
  645. static void fail_requests_for_key(PageantPrivateKey *priv, const char *reason)
  646. {
  647. while (priv->blocked_requests.next != &priv->blocked_requests) {
  648. PageantSignOp *so = container_of(priv->blocked_requests.next,
  649. PageantSignOp, pkr);
  650. signop_unlink(so);
  651. strbuf *sb = strbuf_new();
  652. failure(so->pao.info->pc, so->pao.reqid, sb, so->failure_type,
  653. "%s", reason);
  654. pageant_client_got_response(so->pao.info->pc, so->pao.reqid,
  655. ptrlen_from_strbuf(sb));
  656. strbuf_free(sb);
  657. pageant_async_op_unlink_and_free(&so->pao);
  658. }
  659. }
  660. static void unblock_requests_for_key(PageantPrivateKey *priv)
  661. {
  662. for (PageantKeyRequestNode *pkr = priv->blocked_requests.next;
  663. pkr != &priv->blocked_requests; pkr = pkr->next) {
  664. PageantSignOp *so = container_of(pkr, PageantSignOp, pkr);
  665. queue_toplevel_callback(pageant_async_op_callback, &so->pao);
  666. }
  667. }
  668. static void unblock_pending_gui_requests(void)
  669. {
  670. for (PageantKeyRequestNode *pkr = requests_blocked_on_gui.next;
  671. pkr != &requests_blocked_on_gui; pkr = pkr->next) {
  672. PageantSignOp *so = container_of(pkr, PageantSignOp, pkr);
  673. queue_toplevel_callback(pageant_async_op_callback, &so->pao);
  674. }
  675. }
  676. void pageant_passphrase_request_success(PageantClientDialogId *dlgid,
  677. ptrlen passphrase)
  678. {
  679. PageantPrivateKey *priv = container_of(dlgid, PageantPrivateKey, dlgid);
  680. assert(gui_request_in_progress);
  681. gui_request_in_progress = false;
  682. priv->decryption_prompt_active = false;
  683. if (!priv->skey) {
  684. const char *error;
  685. BinarySource src[1];
  686. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(
  687. priv->encrypted_key_file));
  688. strbuf *ppsb = strbuf_dup_nm(passphrase);
  689. ssh2_userkey *skey = ppk_load_s(src, ppsb->s, &error);
  690. strbuf_free(ppsb);
  691. if (!skey) {
  692. fail_requests_for_key(priv, "unable to decrypt key");
  693. return;
  694. } else if (skey == SSH2_WRONG_PASSPHRASE) {
  695. /*
  696. * Find a PageantClient to use for another attempt at
  697. * request_passphrase.
  698. */
  699. PageantKeyRequestNode *pkr = priv->blocked_requests.next;
  700. if (pkr == &priv->blocked_requests) {
  701. /*
  702. * Special case: if all the requests have gone away at
  703. * this point, we need not bother putting up a request
  704. * at all any more.
  705. */
  706. return;
  707. }
  708. PageantSignOp *so = container_of(priv->blocked_requests.next,
  709. PageantSignOp, pkr);
  710. priv->decryption_prompt_active = false;
  711. if (!request_passphrase(so->pao.info->pc, so->priv)) {
  712. fail_requests_for_key(priv, "unable to continue creating "
  713. "passphrase prompts");
  714. }
  715. return;
  716. } else {
  717. priv->skey = skey->key;
  718. sfree(skey->comment);
  719. sfree(skey);
  720. keylist_update();
  721. }
  722. }
  723. unblock_requests_for_key(priv);
  724. unblock_pending_gui_requests();
  725. }
  726. void pageant_passphrase_request_refused(PageantClientDialogId *dlgid)
  727. {
  728. PageantPrivateKey *priv = container_of(dlgid, PageantPrivateKey, dlgid);
  729. assert(gui_request_in_progress);
  730. gui_request_in_progress = false;
  731. priv->decryption_prompt_active = false;
  732. fail_requests_for_key(priv, "user refused to supply passphrase");
  733. unblock_pending_gui_requests();
  734. }
  735. typedef struct PageantImmOp PageantImmOp;
  736. struct PageantImmOp {
  737. int crLine;
  738. strbuf *response;
  739. PageantAsyncOp pao;
  740. };
  741. static void immop_free(PageantAsyncOp *pao)
  742. {
  743. PageantImmOp *io = container_of(pao, PageantImmOp, pao);
  744. if (io->response)
  745. strbuf_free(io->response);
  746. sfree(io);
  747. }
  748. static void immop_coroutine(PageantAsyncOp *pao)
  749. {
  750. PageantImmOp *io = container_of(pao, PageantImmOp, pao);
  751. crBegin(io->crLine);
  752. if (0) crReturnV;
  753. pageant_client_got_response(io->pao.info->pc, io->pao.reqid,
  754. ptrlen_from_strbuf(io->response));
  755. pageant_async_op_unlink_and_free(&io->pao);
  756. crFinishFreedV;
  757. }
  758. static const PageantAsyncOpVtable immop_vtable = {
  759. .coroutine = immop_coroutine,
  760. .free = immop_free,
  761. };
  762. static bool reencrypt_key(PageantPublicKey *pub)
  763. {
  764. PageantPrivateKey *priv = pub_to_priv(pub);
  765. if (priv->sort.ssh_version != 2) {
  766. /*
  767. * We don't support storing SSH-1 keys in encrypted form at
  768. * all.
  769. */
  770. return false;
  771. }
  772. if (!priv->encrypted_key_file) {
  773. /*
  774. * We can't re-encrypt a key if it doesn't have an encrypted
  775. * form. (We could make one up, of course - but with what
  776. * passphrase that we could expect the user to know later?)
  777. */
  778. return false;
  779. }
  780. /* Only actually free priv->skey if it exists. But we return success
  781. * regardless, so that 'please ensure this key isn't stored
  782. * decrypted' is idempotent. */
  783. if (priv->skey) {
  784. ssh_key_free(priv->skey);
  785. priv->skey = NULL;
  786. }
  787. return true;
  788. }
  789. #define DECL_EXT_ENUM(id, name) id,
  790. enum Extension { KNOWN_EXTENSIONS(DECL_EXT_ENUM) EXT_UNKNOWN };
  791. #define DEF_EXT_NAMES(id, name) PTRLEN_DECL_LITERAL(name),
  792. static const ptrlen extension_names[] = { KNOWN_EXTENSIONS(DEF_EXT_NAMES) };
  793. static PageantAsyncOp *pageant_make_op(
  794. PageantClient *pc, PageantClientRequestId *reqid, ptrlen msgpl)
  795. {
  796. BinarySource msg[1];
  797. strbuf *sb = strbuf_new_nm();
  798. unsigned char failure_type = SSH_AGENT_FAILURE;
  799. int type;
  800. #define fail(...) failure(pc, reqid, sb, failure_type, __VA_ARGS__)
  801. BinarySource_BARE_INIT_PL(msg, msgpl);
  802. type = get_byte(msg);
  803. if (get_err(msg)) {
  804. fail("message contained no type code");
  805. goto responded;
  806. }
  807. switch (type) {
  808. case SSH1_AGENTC_REQUEST_RSA_IDENTITIES: {
  809. /*
  810. * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER.
  811. */
  812. pageant_client_log(pc, reqid,
  813. "request: SSH1_AGENTC_REQUEST_RSA_IDENTITIES");
  814. put_byte(sb, SSH1_AGENT_RSA_IDENTITIES_ANSWER);
  815. pageant_make_keylist1(BinarySink_UPCAST(sb));
  816. pageant_client_log(pc, reqid,
  817. "reply: SSH1_AGENT_RSA_IDENTITIES_ANSWER");
  818. if (!pc->suppress_logging) {
  819. int i;
  820. PageantPublicKey *pub;
  821. for (i = 0; NULL != (pub = pageant_nth_pubkey(1, i)); i++) {
  822. PageantPrivateKey *priv = pub_to_priv(pub);
  823. char *fingerprint = rsa_ssh1_fingerprint(priv->rkey);
  824. pageant_client_log(pc, reqid, "returned key: %s",
  825. fingerprint);
  826. sfree(fingerprint);
  827. }
  828. }
  829. break;
  830. }
  831. case SSH2_AGENTC_REQUEST_IDENTITIES: {
  832. /*
  833. * Reply with SSH2_AGENT_IDENTITIES_ANSWER.
  834. */
  835. pageant_client_log(pc, reqid,
  836. "request: SSH2_AGENTC_REQUEST_IDENTITIES");
  837. put_byte(sb, SSH2_AGENT_IDENTITIES_ANSWER);
  838. pageant_make_keylist2(BinarySink_UPCAST(sb));
  839. pageant_client_log(pc, reqid, "reply: SSH2_AGENT_IDENTITIES_ANSWER");
  840. if (!pc->suppress_logging) {
  841. int i;
  842. PageantPublicKey *pub;
  843. for (i = 0; NULL != (pub = pageant_nth_pubkey(2, i)); i++) {
  844. char *fingerprint = ssh2_double_fingerprint_blob(
  845. pub->sort.full_pub, SSH_FPTYPE_DEFAULT);
  846. pageant_client_log(pc, reqid, "returned key: %s %s",
  847. fingerprint, pub->comment);
  848. sfree(fingerprint);
  849. }
  850. }
  851. break;
  852. }
  853. case SSH1_AGENTC_RSA_CHALLENGE: {
  854. /*
  855. * Reply with either SSH1_AGENT_RSA_RESPONSE or
  856. * SSH_AGENT_FAILURE, depending on whether we have that key
  857. * or not.
  858. */
  859. RSAKey reqkey;
  860. PageantPublicKey *pub;
  861. PageantPrivateKey *priv;
  862. mp_int *challenge, *response;
  863. ptrlen session_id;
  864. unsigned response_type;
  865. unsigned char response_md5[16];
  866. int i;
  867. pageant_client_log(pc, reqid, "request: SSH1_AGENTC_RSA_CHALLENGE");
  868. response = NULL;
  869. memset(&reqkey, 0, sizeof(reqkey));
  870. get_rsa_ssh1_pub(msg, &reqkey, RSA_SSH1_EXPONENT_FIRST);
  871. challenge = get_mp_ssh1(msg);
  872. session_id = get_data(msg, 16);
  873. response_type = get_uint32(msg);
  874. if (get_err(msg)) {
  875. fail("unable to decode request");
  876. goto challenge1_cleanup;
  877. }
  878. if (response_type != 1) {
  879. fail("response type other than 1 not supported");
  880. goto challenge1_cleanup;
  881. }
  882. if (!pc->suppress_logging) {
  883. char *fingerprint;
  884. reqkey.comment = NULL;
  885. fingerprint = rsa_ssh1_fingerprint(&reqkey);
  886. pageant_client_log(pc, reqid, "requested key: %s", fingerprint);
  887. sfree(fingerprint);
  888. }
  889. if ((pub = findpubkey1(&reqkey)) == NULL) {
  890. fail("key not found");
  891. goto challenge1_cleanup;
  892. }
  893. priv = pub_to_priv(pub);
  894. response = rsa_ssh1_decrypt(challenge, priv->rkey);
  895. {
  896. ssh_hash *h = ssh_hash_new(&ssh_md5);
  897. for (i = 0; i < 32; i++)
  898. put_byte(h, mp_get_byte(response, 31 - i));
  899. put_datapl(h, session_id);
  900. ssh_hash_final(h, response_md5);
  901. }
  902. put_byte(sb, SSH1_AGENT_RSA_RESPONSE);
  903. put_data(sb, response_md5, 16);
  904. pageant_client_log(pc, reqid, "reply: SSH1_AGENT_RSA_RESPONSE");
  905. challenge1_cleanup:
  906. if (response)
  907. mp_free(response);
  908. mp_free(challenge);
  909. freersakey(&reqkey);
  910. break;
  911. }
  912. case SSH2_AGENTC_SIGN_REQUEST: {
  913. /*
  914. * Reply with either SSH2_AGENT_SIGN_RESPONSE or
  915. * SSH_AGENT_FAILURE, depending on whether we have that key
  916. * or not.
  917. */
  918. PageantPublicKey *pub;
  919. ptrlen keyblob, sigdata;
  920. uint32_t flags;
  921. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_SIGN_REQUEST");
  922. keyblob = get_string(msg);
  923. sigdata = get_string(msg);
  924. if (get_err(msg)) {
  925. fail("unable to decode request");
  926. goto responded;
  927. }
  928. /*
  929. * Later versions of the agent protocol added a flags word
  930. * on the end of the sign request. That hasn't always been
  931. * there, so we don't complain if we don't find it.
  932. *
  933. * get_uint32 will default to returning zero if no data is
  934. * available.
  935. */
  936. bool have_flags = false;
  937. flags = get_uint32(msg);
  938. if (!get_err(msg))
  939. have_flags = true;
  940. if (!pc->suppress_logging) {
  941. char *fingerprint = ssh2_double_fingerprint_blob(
  942. keyblob, SSH_FPTYPE_DEFAULT);
  943. pageant_client_log(pc, reqid, "requested key: %s", fingerprint);
  944. sfree(fingerprint);
  945. }
  946. if ((pub = findpubkey2(keyblob)) == NULL) {
  947. fail("key not found");
  948. goto responded;
  949. }
  950. if (have_flags)
  951. pageant_client_log(pc, reqid, "signature flags = 0x%08"PRIx32,
  952. flags);
  953. else
  954. pageant_client_log(pc, reqid, "no signature flags");
  955. strbuf_free(sb); /* no immediate response */
  956. PageantSignOp *so = snew(PageantSignOp);
  957. so->pao.vt = &signop_vtable;
  958. so->pao.info = pc->info;
  959. so->pao.cr.prev = pc->info->head.prev;
  960. so->pao.cr.next = &pc->info->head;
  961. so->pao.cr.prev->next = so->pao.cr.next->prev = &so->pao.cr;
  962. so->pao.reqid = reqid;
  963. so->priv = pub_to_priv(pub);
  964. so->pkr.prev = so->pkr.next = NULL;
  965. so->data_to_sign = strbuf_dup(sigdata);
  966. so->flags = flags;
  967. so->failure_type = failure_type;
  968. so->crLine = 0;
  969. return &so->pao;
  970. break;
  971. }
  972. case SSH1_AGENTC_ADD_RSA_IDENTITY: {
  973. /*
  974. * Add to the list and return SSH_AGENT_SUCCESS, or
  975. * SSH_AGENT_FAILURE if the key was malformed.
  976. */
  977. RSAKey *key;
  978. pageant_client_log(pc, reqid, "request: SSH1_AGENTC_ADD_RSA_IDENTITY");
  979. key = get_rsa_ssh1_priv_agent(msg);
  980. key->comment = mkstr(get_string(msg));
  981. if (get_err(msg)) {
  982. fail("unable to decode request");
  983. goto add1_cleanup;
  984. }
  985. if (!rsa_verify(key)) {
  986. fail("key is invalid");
  987. goto add1_cleanup;
  988. }
  989. if (!pc->suppress_logging) {
  990. char *fingerprint = rsa_ssh1_fingerprint(key);
  991. pageant_client_log(pc, reqid,
  992. "submitted key: %s", fingerprint);
  993. sfree(fingerprint);
  994. }
  995. if (pageant_add_ssh1_key(key)) {
  996. keylist_update();
  997. put_byte(sb, SSH_AGENT_SUCCESS);
  998. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  999. key = NULL; /* don't free it in cleanup */
  1000. } else {
  1001. fail("key already present");
  1002. }
  1003. add1_cleanup:
  1004. if (key) {
  1005. freersakey(key);
  1006. sfree(key);
  1007. }
  1008. break;
  1009. }
  1010. case SSH2_AGENTC_ADD_IDENTITY: {
  1011. /*
  1012. * Add to the list and return SSH_AGENT_SUCCESS, or
  1013. * SSH_AGENT_FAILURE if the key was malformed.
  1014. */
  1015. ssh2_userkey *key = NULL;
  1016. ptrlen algpl;
  1017. const ssh_keyalg *alg;
  1018. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_ADD_IDENTITY");
  1019. algpl = get_string(msg);
  1020. key = snew(ssh2_userkey);
  1021. key->key = NULL;
  1022. key->comment = NULL;
  1023. alg = find_pubkey_alg_len(algpl);
  1024. if (!alg) {
  1025. fail("algorithm unknown");
  1026. goto add2_cleanup;
  1027. }
  1028. key->key = ssh_key_new_priv_openssh(alg, msg);
  1029. if (!key->key) {
  1030. fail("key setup failed");
  1031. goto add2_cleanup;
  1032. }
  1033. key->comment = mkstr(get_string(msg));
  1034. if (get_err(msg)) {
  1035. fail("unable to decode request");
  1036. goto add2_cleanup;
  1037. }
  1038. if (!pc->suppress_logging) {
  1039. char *fingerprint = ssh2_fingerprint(key->key, SSH_FPTYPE_DEFAULT);
  1040. pageant_client_log(pc, reqid, "submitted key: %s %s",
  1041. fingerprint, key->comment);
  1042. sfree(fingerprint);
  1043. }
  1044. if (pageant_add_ssh2_key(key)) {
  1045. keylist_update();
  1046. put_byte(sb, SSH_AGENT_SUCCESS);
  1047. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1048. key = NULL; /* don't clean it up */
  1049. } else {
  1050. fail("key already present");
  1051. }
  1052. add2_cleanup:
  1053. if (key) {
  1054. if (key->key)
  1055. ssh_key_free(key->key);
  1056. if (key->comment)
  1057. sfree(key->comment);
  1058. sfree(key);
  1059. }
  1060. break;
  1061. }
  1062. case SSH1_AGENTC_REMOVE_RSA_IDENTITY: {
  1063. /*
  1064. * Remove from the list and return SSH_AGENT_SUCCESS, or
  1065. * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
  1066. * start with.
  1067. */
  1068. RSAKey reqkey;
  1069. PageantPublicKey *pub;
  1070. pageant_client_log(pc, reqid,
  1071. "request: SSH1_AGENTC_REMOVE_RSA_IDENTITY");
  1072. memset(&reqkey, 0, sizeof(reqkey));
  1073. get_rsa_ssh1_pub(msg, &reqkey, RSA_SSH1_EXPONENT_FIRST);
  1074. if (get_err(msg)) {
  1075. fail("unable to decode request");
  1076. freersakey(&reqkey);
  1077. goto responded;
  1078. }
  1079. if (!pc->suppress_logging) {
  1080. char *fingerprint;
  1081. reqkey.comment = NULL;
  1082. fingerprint = rsa_ssh1_fingerprint(&reqkey);
  1083. pageant_client_log(pc, reqid, "unwanted key: %s", fingerprint);
  1084. sfree(fingerprint);
  1085. }
  1086. pub = findpubkey1(&reqkey);
  1087. freersakey(&reqkey);
  1088. if (pub) {
  1089. pageant_client_log(pc, reqid, "found with comment: %s",
  1090. pub->comment);
  1091. del_pubkey(pub);
  1092. keylist_update();
  1093. pk_pub_free(pub);
  1094. put_byte(sb, SSH_AGENT_SUCCESS);
  1095. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1096. } else {
  1097. fail("key not found");
  1098. }
  1099. break;
  1100. }
  1101. case SSH2_AGENTC_REMOVE_IDENTITY: {
  1102. /*
  1103. * Remove from the list and return SSH_AGENT_SUCCESS, or
  1104. * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
  1105. * start with.
  1106. */
  1107. PageantPublicKey *pub;
  1108. ptrlen blob;
  1109. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_REMOVE_IDENTITY");
  1110. blob = get_string(msg);
  1111. if (get_err(msg)) {
  1112. fail("unable to decode request");
  1113. goto responded;
  1114. }
  1115. if (!pc->suppress_logging) {
  1116. char *fingerprint = ssh2_double_fingerprint_blob(
  1117. blob, SSH_FPTYPE_DEFAULT);
  1118. pageant_client_log(pc, reqid, "unwanted key: %s", fingerprint);
  1119. sfree(fingerprint);
  1120. }
  1121. pub = findpubkey2(blob);
  1122. if (!pub) {
  1123. fail("key not found");
  1124. goto responded;
  1125. }
  1126. pageant_client_log(pc, reqid, "found with comment: %s", pub->comment);
  1127. del_pubkey(pub);
  1128. keylist_update();
  1129. pk_pub_free(pub);
  1130. put_byte(sb, SSH_AGENT_SUCCESS);
  1131. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1132. break;
  1133. }
  1134. case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES: {
  1135. /*
  1136. * Remove all SSH-1 keys. Always returns success.
  1137. */
  1138. pageant_client_log(pc, reqid,
  1139. "request: SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES");
  1140. remove_all_keys(1);
  1141. keylist_update();
  1142. put_byte(sb, SSH_AGENT_SUCCESS);
  1143. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1144. break;
  1145. }
  1146. case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: {
  1147. /*
  1148. * Remove all SSH-2 keys. Always returns success.
  1149. */
  1150. pageant_client_log(pc, reqid,
  1151. "request: SSH2_AGENTC_REMOVE_ALL_IDENTITIES");
  1152. remove_all_keys(2);
  1153. keylist_update();
  1154. put_byte(sb, SSH_AGENT_SUCCESS);
  1155. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1156. break;
  1157. }
  1158. case SSH2_AGENTC_EXTENSION: {
  1159. enum Extension exttype = EXT_UNKNOWN;
  1160. ptrlen extname = get_string(msg);
  1161. pageant_client_log(pc, reqid,
  1162. "request: SSH2_AGENTC_EXTENSION \"%.*s\"",
  1163. PTRLEN_PRINTF(extname));
  1164. for (size_t i = 0; i < lenof(extension_names); i++)
  1165. if (ptrlen_eq_ptrlen(extname, extension_names[i])) {
  1166. exttype = i;
  1167. /*
  1168. * For SSH_AGENTC_EXTENSION requests, the message
  1169. * code SSH_AGENT_FAILURE is reserved for "I don't
  1170. * recognise this extension name at all". For any
  1171. * other kind of failure while processing an
  1172. * extension we _do_ recognise, we must switch to
  1173. * returning a different failure code, with
  1174. * semantics "I understood the extension name, but
  1175. * something else went wrong".
  1176. */
  1177. failure_type = SSH_AGENT_EXTENSION_FAILURE;
  1178. break;
  1179. }
  1180. switch (exttype) {
  1181. case EXT_UNKNOWN:
  1182. fail("unrecognised extension name '%.*s'",
  1183. PTRLEN_PRINTF(extname));
  1184. break;
  1185. case EXT_QUERY:
  1186. /* Standard request to list the supported extensions. */
  1187. put_byte(sb, SSH_AGENT_SUCCESS);
  1188. for (size_t i = 0; i < lenof(extension_names); i++)
  1189. put_stringpl(sb, extension_names[i]);
  1190. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS + names");
  1191. break;
  1192. case EXT_ADD_PPK: {
  1193. ptrlen keyfile = get_string(msg);
  1194. if (get_err(msg)) {
  1195. fail("unable to decode request");
  1196. goto responded;
  1197. }
  1198. strbuf *base_pub = NULL;
  1199. strbuf *full_pub = NULL;
  1200. BinarySource src[1];
  1201. const char *error;
  1202. full_pub = strbuf_new();
  1203. char *comment;
  1204. BinarySource_BARE_INIT_PL(src, keyfile);
  1205. if (!ppk_loadpub_s(src, NULL, BinarySink_UPCAST(full_pub),
  1206. &comment, &error)) {
  1207. fail("failed to extract public key blob: %s", error);
  1208. goto add_ppk_cleanup;
  1209. }
  1210. if (!pc->suppress_logging) {
  1211. char *fingerprint = ssh2_double_fingerprint_blob(
  1212. ptrlen_from_strbuf(full_pub), SSH_FPTYPE_DEFAULT);
  1213. pageant_client_log(pc, reqid, "add-ppk: %s %s",
  1214. fingerprint, comment);
  1215. sfree(fingerprint);
  1216. }
  1217. BinarySource_BARE_INIT_PL(src, keyfile);
  1218. bool encrypted = ppk_encrypted_s(src, NULL);
  1219. if (!encrypted) {
  1220. /* If the key isn't encrypted, then we should just
  1221. * load and add it in the obvious way. */
  1222. BinarySource_BARE_INIT_PL(src, keyfile);
  1223. ssh2_userkey *skey = ppk_load_s(src, NULL, &error);
  1224. if (!skey) {
  1225. fail("failed to decode private key: %s", error);
  1226. } else if (pageant_add_ssh2_key(skey)) {
  1227. keylist_update();
  1228. put_byte(sb, SSH_AGENT_SUCCESS);
  1229. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS"
  1230. " (loaded unencrypted PPK)");
  1231. } else {
  1232. fail("key already present");
  1233. if (skey->key)
  1234. ssh_key_free(skey->key);
  1235. if (skey->comment)
  1236. sfree(skey->comment);
  1237. sfree(skey);
  1238. }
  1239. goto add_ppk_cleanup;
  1240. }
  1241. PageantPublicKeySort sort;
  1242. sort.priv.ssh_version = 2;
  1243. sort.full_pub = ptrlen_from_strbuf(full_pub);
  1244. base_pub = make_base_pub_2(&sort);
  1245. pageant_add_ssh2_key_encrypted(sort, comment, keyfile);
  1246. keylist_update();
  1247. put_byte(sb, SSH_AGENT_SUCCESS);
  1248. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1249. add_ppk_cleanup:
  1250. if (full_pub)
  1251. strbuf_free(full_pub);
  1252. if (base_pub)
  1253. strbuf_free(base_pub);
  1254. sfree(comment);
  1255. break;
  1256. }
  1257. case EXT_REENCRYPT: {
  1258. /*
  1259. * Re-encrypt a single key, in the sense of deleting
  1260. * its unencrypted copy, returning it to the state of
  1261. * only having the encrypted PPK form stored, so that
  1262. * the next attempt to use it will have to re-prompt
  1263. * for the passphrase.
  1264. */
  1265. ptrlen blob = get_string(msg);
  1266. if (get_err(msg)) {
  1267. fail("unable to decode request");
  1268. goto responded;
  1269. }
  1270. if (!pc->suppress_logging) {
  1271. char *fingerprint = ssh2_double_fingerprint_blob(
  1272. blob, SSH_FPTYPE_DEFAULT);
  1273. pageant_client_log(pc, reqid, "key to re-encrypt: %s",
  1274. fingerprint);
  1275. sfree(fingerprint);
  1276. }
  1277. PageantPublicKey *pub = findpubkey2(blob);
  1278. if (!pub) {
  1279. fail("key not found");
  1280. goto responded;
  1281. }
  1282. pageant_client_log(pc, reqid,
  1283. "found with comment: %s", pub->comment);
  1284. if (!reencrypt_key(pub)) {
  1285. fail("this key couldn't be re-encrypted");
  1286. goto responded;
  1287. }
  1288. keylist_update();
  1289. put_byte(sb, SSH_AGENT_SUCCESS);
  1290. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1291. break;
  1292. }
  1293. case EXT_REENCRYPT_ALL: {
  1294. /*
  1295. * Re-encrypt all keys that have an encrypted form
  1296. * stored. Usually, returns success, but with a uint32
  1297. * appended indicating how many keys remain
  1298. * unencrypted. The exception is if there is at least
  1299. * one key in the agent and _no_ key was successfully
  1300. * re-encrypted; in that situation we've done nothing,
  1301. * and the client didn't _want_ us to do nothing, so
  1302. * we return failure.
  1303. *
  1304. * (Rationale: the 'failure' message ought to be
  1305. * atomic, that is, you shouldn't return failure
  1306. * having made a state change.)
  1307. */
  1308. unsigned nfailures = 0, nsuccesses = 0;
  1309. PageantPublicKey *pub;
  1310. for (int i = 0; (pub = index234(pubkeytree, i)) != NULL; i++) {
  1311. if (reencrypt_key(pub))
  1312. nsuccesses++;
  1313. else
  1314. nfailures++;
  1315. }
  1316. if (nsuccesses == 0 && nfailures > 0) {
  1317. fail("no key could be re-encrypted");
  1318. } else {
  1319. keylist_update();
  1320. put_byte(sb, SSH_AGENT_SUCCESS);
  1321. put_uint32(sb, nfailures);
  1322. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS "
  1323. "(%u keys re-encrypted, %u failures)",
  1324. nsuccesses, nfailures);
  1325. }
  1326. break;
  1327. }
  1328. case EXT_LIST_EXTENDED: {
  1329. /*
  1330. * Return a key list like SSH2_AGENTC_REQUEST_IDENTITIES,
  1331. * except that each key is annotated with extra
  1332. * information such as whether it's currently encrypted.
  1333. *
  1334. * The return message type is AGENT_SUCCESS with auxiliary
  1335. * data, which is more like other extension messages. I
  1336. * think it would be confusing to reuse IDENTITIES_ANSWER
  1337. * for a reply message with an incompatible format.
  1338. */
  1339. put_byte(sb, SSH_AGENT_SUCCESS);
  1340. pageant_make_keylist_extended(BinarySink_UPCAST(sb));
  1341. pageant_client_log(pc, reqid,
  1342. "reply: SSH2_AGENT_SUCCESS + key list");
  1343. if (!pc->suppress_logging) {
  1344. int i;
  1345. PageantPublicKey *pub;
  1346. for (i = 0; NULL != (pub = pageant_nth_pubkey(2, i)); i++) {
  1347. char *fingerprint = ssh2_double_fingerprint_blob(
  1348. ptrlen_from_strbuf(pub->full_pub),
  1349. SSH_FPTYPE_DEFAULT);
  1350. pageant_client_log(pc, reqid, "returned key: %s %s",
  1351. fingerprint, pub->comment);
  1352. sfree(fingerprint);
  1353. }
  1354. }
  1355. break;
  1356. }
  1357. }
  1358. break;
  1359. }
  1360. default:
  1361. pageant_client_log(pc, reqid, "request: unknown message type %d",
  1362. type);
  1363. fail("unrecognised message");
  1364. break;
  1365. }
  1366. #undef fail
  1367. responded:;
  1368. PageantImmOp *io = snew(PageantImmOp);
  1369. io->pao.vt = &immop_vtable;
  1370. io->pao.info = pc->info;
  1371. io->pao.cr.prev = pc->info->head.prev;
  1372. io->pao.cr.next = &pc->info->head;
  1373. io->pao.cr.prev->next = io->pao.cr.next->prev = &io->pao.cr;
  1374. io->pao.reqid = reqid;
  1375. io->response = sb;
  1376. io->crLine = 0;
  1377. return &io->pao;
  1378. }
  1379. void pageant_handle_msg(PageantClient *pc, PageantClientRequestId *reqid,
  1380. ptrlen msgpl)
  1381. {
  1382. PageantAsyncOp *pao = pageant_make_op(pc, reqid, msgpl);
  1383. queue_toplevel_callback(pageant_async_op_callback, pao);
  1384. }
  1385. void pageant_init(void)
  1386. {
  1387. pageant_local = true;
  1388. pubkeytree = newtree234(pubkey_cmpfn);
  1389. privkeytree = newtree234(privkey_cmpfn);
  1390. }
  1391. static PageantPublicKey *pageant_nth_pubkey(int ssh_version, int i)
  1392. {
  1393. PageantPublicKey *pub = index234(
  1394. pubkeytree, find_first_pubkey_for_version(ssh_version) + i);
  1395. if (pub && pub->sort.priv.ssh_version == ssh_version)
  1396. return pub;
  1397. else
  1398. return NULL;
  1399. }
  1400. bool pageant_delete_nth_ssh1_key(int i)
  1401. {
  1402. PageantPublicKey *pub = del_pubkey_pos(
  1403. find_first_pubkey_for_version(1) + i);
  1404. if (!pub)
  1405. return false;
  1406. pk_pub_free(pub);
  1407. return true;
  1408. }
  1409. bool pageant_delete_nth_ssh2_key(int i)
  1410. {
  1411. PageantPublicKey *pub = del_pubkey_pos(
  1412. find_first_pubkey_for_version(2) + i);
  1413. if (!pub)
  1414. return false;
  1415. pk_pub_free(pub);
  1416. return true;
  1417. }
  1418. bool pageant_reencrypt_nth_ssh2_key(int i)
  1419. {
  1420. PageantPublicKey *pub = index234(
  1421. pubkeytree, find_first_pubkey_for_version(2) + i);
  1422. if (!pub)
  1423. return false;
  1424. return reencrypt_key(pub);
  1425. }
  1426. void pageant_delete_all(void)
  1427. {
  1428. remove_all_keys(1);
  1429. remove_all_keys(2);
  1430. }
  1431. void pageant_reencrypt_all(void)
  1432. {
  1433. PageantPublicKey *pub;
  1434. for (int i = 0; (pub = index234(pubkeytree, i)) != NULL; i++)
  1435. reencrypt_key(pub);
  1436. }
  1437. /* ----------------------------------------------------------------------
  1438. * The agent plug.
  1439. */
  1440. /*
  1441. * An extra coroutine macro, specific to this code which is consuming
  1442. * 'const char *data'.
  1443. */
  1444. #define crGetChar(c) do \
  1445. { \
  1446. while (len == 0) { \
  1447. *crLine = __LINE__; return; case __LINE__:; \
  1448. } \
  1449. len--; \
  1450. (c) = (unsigned char)*data++; \
  1451. } while (0)
  1452. struct pageant_conn_queued_response {
  1453. struct pageant_conn_queued_response *next, *prev;
  1454. size_t req_index; /* for indexing requests in log messages */
  1455. strbuf *sb;
  1456. PageantClientRequestId reqid;
  1457. };
  1458. struct pageant_conn_state {
  1459. Socket *connsock;
  1460. PageantListenerClient *plc;
  1461. unsigned char lenbuf[4], pktbuf[AGENT_MAX_MSGLEN];
  1462. unsigned len, got;
  1463. bool real_packet;
  1464. size_t conn_index; /* for indexing connections in log messages */
  1465. size_t req_index; /* for indexing requests in log messages */
  1466. int crLine; /* for coroutine in pageant_conn_receive */
  1467. struct pageant_conn_queued_response response_queue;
  1468. PageantClient pc;
  1469. Plug plug;
  1470. };
  1471. static void pageant_conn_closing(Plug *plug, PlugCloseType type,
  1472. const char *error_msg)
  1473. {
  1474. struct pageant_conn_state *pc = container_of(
  1475. plug, struct pageant_conn_state, plug);
  1476. if (type != PLUGCLOSE_NORMAL)
  1477. pageant_listener_client_log(pc->plc, "c#%"SIZEu": error: %s",
  1478. pc->conn_index, error_msg);
  1479. else
  1480. pageant_listener_client_log(pc->plc, "c#%"SIZEu": connection closed",
  1481. pc->conn_index);
  1482. sk_close(pc->connsock);
  1483. pageant_unregister_client(&pc->pc);
  1484. sfree(pc);
  1485. }
  1486. static void pageant_conn_sent(Plug *plug, size_t bufsize)
  1487. {
  1488. /* struct pageant_conn_state *pc = container_of(
  1489. plug, struct pageant_conn_state, plug); */
  1490. /*
  1491. * We do nothing here, because we expect that there won't be a
  1492. * need to throttle and unthrottle the connection to an agent -
  1493. * clients will typically not send many requests, and will wait
  1494. * until they receive each reply before sending a new request.
  1495. */
  1496. }
  1497. static void pageant_conn_log(PageantClient *pc, PageantClientRequestId *reqid,
  1498. const char *fmt, va_list ap)
  1499. {
  1500. struct pageant_conn_state *pcs =
  1501. container_of(pc, struct pageant_conn_state, pc);
  1502. struct pageant_conn_queued_response *qr =
  1503. container_of(reqid, struct pageant_conn_queued_response, reqid);
  1504. char *formatted = dupvprintf(fmt, ap);
  1505. pageant_listener_client_log(pcs->plc, "c#%"SIZEu",r#%"SIZEu": %s",
  1506. pcs->conn_index, qr->req_index, formatted);
  1507. sfree(formatted);
  1508. }
  1509. static void pageant_conn_got_response(
  1510. PageantClient *pc, PageantClientRequestId *reqid, ptrlen response)
  1511. {
  1512. struct pageant_conn_state *pcs =
  1513. container_of(pc, struct pageant_conn_state, pc);
  1514. struct pageant_conn_queued_response *qr =
  1515. container_of(reqid, struct pageant_conn_queued_response, reqid);
  1516. qr->sb = strbuf_new_nm();
  1517. put_stringpl(qr->sb, response);
  1518. while (pcs->response_queue.next != &pcs->response_queue &&
  1519. pcs->response_queue.next->sb) {
  1520. qr = pcs->response_queue.next;
  1521. sk_write(pcs->connsock, qr->sb->u, qr->sb->len);
  1522. qr->next->prev = qr->prev;
  1523. qr->prev->next = qr->next;
  1524. strbuf_free(qr->sb);
  1525. sfree(qr);
  1526. }
  1527. }
  1528. static bool pageant_conn_ask_passphrase(
  1529. PageantClient *pc, PageantClientDialogId *dlgid, const char *comment)
  1530. {
  1531. struct pageant_conn_state *pcs =
  1532. container_of(pc, struct pageant_conn_state, pc);
  1533. return pageant_listener_client_ask_passphrase(pcs->plc, dlgid, comment);
  1534. }
  1535. static const PageantClientVtable pageant_connection_clientvt = {
  1536. .log = pageant_conn_log,
  1537. .got_response = pageant_conn_got_response,
  1538. .ask_passphrase = pageant_conn_ask_passphrase,
  1539. };
  1540. static void pageant_conn_receive(
  1541. Plug *plug, int urgent, const char *data, size_t len)
  1542. {
  1543. struct pageant_conn_state *pc = container_of(
  1544. plug, struct pageant_conn_state, plug);
  1545. char c;
  1546. crBegin(pc->crLine);
  1547. while (len > 0) {
  1548. pc->got = 0;
  1549. while (pc->got < 4) {
  1550. crGetChar(c);
  1551. pc->lenbuf[pc->got++] = c;
  1552. }
  1553. pc->len = GET_32BIT_MSB_FIRST(pc->lenbuf);
  1554. pc->got = 0;
  1555. pc->real_packet = (pc->len < AGENT_MAX_MSGLEN-4);
  1556. {
  1557. struct pageant_conn_queued_response *qr =
  1558. snew(struct pageant_conn_queued_response);
  1559. qr->prev = pc->response_queue.prev;
  1560. qr->next = &pc->response_queue;
  1561. qr->prev->next = qr->next->prev = qr;
  1562. qr->sb = NULL;
  1563. qr->req_index = pc->req_index++;
  1564. }
  1565. if (!pc->real_packet) {
  1566. /*
  1567. * Send failure immediately, before consuming the packet
  1568. * data. That way we notify the client reasonably early
  1569. * even if the data channel has just started spewing
  1570. * nonsense.
  1571. */
  1572. pageant_client_log(&pc->pc, &pc->response_queue.prev->reqid,
  1573. "early reply: SSH_AGENT_FAILURE "
  1574. "(overlong message, length %u)", pc->len);
  1575. static const unsigned char failure[] = { SSH_AGENT_FAILURE };
  1576. pageant_conn_got_response(&pc->pc, &pc->response_queue.prev->reqid,
  1577. make_ptrlen(failure, lenof(failure)));
  1578. }
  1579. while (pc->got < pc->len) {
  1580. crGetChar(c);
  1581. if (pc->real_packet)
  1582. pc->pktbuf[pc->got] = c;
  1583. pc->got++;
  1584. }
  1585. if (pc->real_packet)
  1586. pageant_handle_msg(&pc->pc, &pc->response_queue.prev->reqid,
  1587. make_ptrlen(pc->pktbuf, pc->len));
  1588. }
  1589. crFinishV;
  1590. }
  1591. struct pageant_listen_state {
  1592. Socket *listensock;
  1593. PageantListenerClient *plc;
  1594. size_t conn_index; /* for indexing connections in log messages */
  1595. Plug plug;
  1596. };
  1597. static void pageant_listen_closing(Plug *plug, PlugCloseType type,
  1598. const char *error_msg)
  1599. {
  1600. struct pageant_listen_state *pl = container_of(
  1601. plug, struct pageant_listen_state, plug);
  1602. if (type != PLUGCLOSE_NORMAL)
  1603. pageant_listener_client_log(pl->plc, "listening socket: error: %s",
  1604. error_msg);
  1605. sk_close(pl->listensock);
  1606. pl->listensock = NULL;
  1607. }
  1608. static const PlugVtable pageant_connection_plugvt = {
  1609. .closing = pageant_conn_closing,
  1610. .receive = pageant_conn_receive,
  1611. .sent = pageant_conn_sent,
  1612. .log = nullplug_log,
  1613. };
  1614. static int pageant_listen_accepting(Plug *plug,
  1615. accept_fn_t constructor, accept_ctx_t ctx)
  1616. {
  1617. struct pageant_listen_state *pl = container_of(
  1618. plug, struct pageant_listen_state, plug);
  1619. struct pageant_conn_state *pc;
  1620. const char *err;
  1621. SocketEndpointInfo *peerinfo;
  1622. pc = snew(struct pageant_conn_state);
  1623. pc->plug.vt = &pageant_connection_plugvt;
  1624. pc->pc.vt = &pageant_connection_clientvt;
  1625. pc->plc = pl->plc;
  1626. pc->response_queue.next = pc->response_queue.prev = &pc->response_queue;
  1627. pc->conn_index = pl->conn_index++;
  1628. pc->req_index = 0;
  1629. pc->crLine = 0;
  1630. pc->connsock = constructor(ctx, &pc->plug);
  1631. if ((err = sk_socket_error(pc->connsock)) != NULL) {
  1632. sk_close(pc->connsock);
  1633. sfree(pc);
  1634. return 1;
  1635. }
  1636. sk_set_frozen(pc->connsock, false);
  1637. peerinfo = sk_peer_info(pc->connsock);
  1638. if (peerinfo && peerinfo->log_text) {
  1639. pageant_listener_client_log(pl->plc,
  1640. "c#%"SIZEu": new connection from %s",
  1641. pc->conn_index, peerinfo->log_text);
  1642. } else {
  1643. pageant_listener_client_log(pl->plc, "c#%"SIZEu": new connection",
  1644. pc->conn_index);
  1645. }
  1646. sk_free_endpoint_info(peerinfo);
  1647. pageant_register_client(&pc->pc);
  1648. return 0;
  1649. }
  1650. static const PlugVtable pageant_listener_plugvt = {
  1651. .closing = pageant_listen_closing,
  1652. .accepting = pageant_listen_accepting,
  1653. .log = nullplug_log,
  1654. };
  1655. struct pageant_listen_state *pageant_listener_new(
  1656. Plug **plug, PageantListenerClient *plc)
  1657. {
  1658. struct pageant_listen_state *pl = snew(struct pageant_listen_state);
  1659. pl->plug.vt = &pageant_listener_plugvt;
  1660. pl->plc = plc;
  1661. pl->listensock = NULL;
  1662. pl->conn_index = 0;
  1663. *plug = &pl->plug;
  1664. return pl;
  1665. }
  1666. void pageant_listener_got_socket(struct pageant_listen_state *pl, Socket *sock)
  1667. {
  1668. pl->listensock = sock;
  1669. }
  1670. void pageant_listener_free(struct pageant_listen_state *pl)
  1671. {
  1672. if (pl->listensock)
  1673. sk_close(pl->listensock);
  1674. sfree(pl);
  1675. }
  1676. /* ----------------------------------------------------------------------
  1677. * Code to perform agent operations either as a client, or within the
  1678. * same process as the running agent.
  1679. */
  1680. static tree234 *passphrases = NULL;
  1681. typedef struct PageantInternalClient {
  1682. strbuf *response;
  1683. bool got_response;
  1684. PageantClient pc;
  1685. } PageantInternalClient;
  1686. static void internal_client_got_response(
  1687. PageantClient *pc, PageantClientRequestId *reqid, ptrlen response)
  1688. {
  1689. PageantInternalClient *pic = container_of(pc, PageantInternalClient, pc);
  1690. strbuf_clear(pic->response);
  1691. put_datapl(pic->response, response);
  1692. pic->got_response = true;
  1693. }
  1694. static bool internal_client_ask_passphrase(
  1695. PageantClient *pc, PageantClientDialogId *dlgid, const char *comment)
  1696. {
  1697. /* No delaying operations are permitted in this mode */
  1698. return false;
  1699. }
  1700. static const PageantClientVtable internal_clientvt = {
  1701. .log = NULL,
  1702. .got_response = internal_client_got_response,
  1703. .ask_passphrase = internal_client_ask_passphrase,
  1704. };
  1705. typedef struct PageantClientOp {
  1706. strbuf *buf;
  1707. bool request_made;
  1708. BinarySink_DELEGATE_IMPLEMENTATION;
  1709. BinarySource_IMPLEMENTATION;
  1710. } PageantClientOp;
  1711. static PageantClientOp *pageant_client_op_new(void)
  1712. {
  1713. PageantClientOp *pco = snew(PageantClientOp);
  1714. pco->buf = strbuf_new_for_agent_query();
  1715. pco->request_made = false;
  1716. BinarySink_DELEGATE_INIT(pco, pco->buf);
  1717. BinarySource_INIT(pco, "", 0);
  1718. return pco;
  1719. }
  1720. static void pageant_client_op_free(PageantClientOp *pco)
  1721. {
  1722. if (pco->buf)
  1723. strbuf_free(pco->buf);
  1724. sfree(pco);
  1725. }
  1726. static unsigned pageant_client_op_query(PageantClientOp *pco)
  1727. {
  1728. /* Since we use the same strbuf for the request and the response,
  1729. * check by assertion that we aren't embarrassingly sending a
  1730. * previous response back to the agent */
  1731. assert(!pco->request_made);
  1732. pco->request_made = true;
  1733. if (!pageant_local) {
  1734. void *response_raw;
  1735. int resplen_raw;
  1736. agent_query_synchronous(pco->buf, &response_raw, &resplen_raw);
  1737. strbuf_clear(pco->buf);
  1738. put_data(pco->buf, response_raw, resplen_raw);
  1739. sfree(response_raw);
  1740. /* The data coming back from agent_query_synchronous will have
  1741. * its length field prepended. So we start by parsing it as an
  1742. * SSH-formatted string, and then reinitialise our
  1743. * BinarySource with the interior of that string. */
  1744. BinarySource_INIT_PL(pco, ptrlen_from_strbuf(pco->buf));
  1745. BinarySource_INIT_PL(pco, get_string(pco));
  1746. } else {
  1747. PageantInternalClient pic;
  1748. PageantClientRequestId reqid;
  1749. pic.pc.vt = &internal_clientvt;
  1750. pic.pc.suppress_logging = true;
  1751. pic.response = pco->buf;
  1752. pic.got_response = false;
  1753. pageant_register_client(&pic.pc);
  1754. assert(pco->buf->len > 4);
  1755. PageantAsyncOp *pao = pageant_make_op(
  1756. &pic.pc, &reqid, make_ptrlen(pco->buf->s + 4, pco->buf->len - 4));
  1757. while (!pic.got_response)
  1758. pageant_async_op_coroutine(pao);
  1759. pageant_unregister_client(&pic.pc);
  1760. BinarySource_INIT_PL(pco, ptrlen_from_strbuf(pco->buf));
  1761. }
  1762. /* Strip off and directly return the type byte, which every client
  1763. * will need, to save a boilerplate get_byte at each call site */
  1764. unsigned reply_type = get_byte(pco);
  1765. if (get_err(pco))
  1766. reply_type = 256; /* out-of-range code */
  1767. return reply_type;
  1768. }
  1769. /*
  1770. * After processing a list of filenames, we want to forget the
  1771. * passphrases.
  1772. */
  1773. void pageant_forget_passphrases(void)
  1774. {
  1775. if (!passphrases) /* in case we never set it up at all */
  1776. return;
  1777. while (count234(passphrases) > 0) {
  1778. char *pp = index234(passphrases, 0);
  1779. smemclr(pp, strlen(pp));
  1780. delpos234(passphrases, 0);
  1781. sfree(pp);
  1782. }
  1783. }
  1784. typedef struct KeyListEntry {
  1785. ptrlen blob, comment;
  1786. uint32_t flags;
  1787. } KeyListEntry;
  1788. typedef struct KeyList {
  1789. strbuf *raw_data;
  1790. KeyListEntry *keys;
  1791. size_t nkeys;
  1792. bool broken;
  1793. } KeyList;
  1794. static void keylist_free(KeyList *kl)
  1795. {
  1796. sfree(kl->keys);
  1797. strbuf_free(kl->raw_data);
  1798. sfree(kl);
  1799. }
  1800. static PageantClientOp *pageant_request_keylist_1(void)
  1801. {
  1802. PageantClientOp *pco = pageant_client_op_new();
  1803. put_byte(pco, SSH1_AGENTC_REQUEST_RSA_IDENTITIES);
  1804. if (pageant_client_op_query(pco) == SSH1_AGENT_RSA_IDENTITIES_ANSWER)
  1805. return pco;
  1806. pageant_client_op_free(pco);
  1807. return NULL;
  1808. }
  1809. static PageantClientOp *pageant_request_keylist_2(void)
  1810. {
  1811. PageantClientOp *pco = pageant_client_op_new();
  1812. put_byte(pco, SSH2_AGENTC_REQUEST_IDENTITIES);
  1813. if (pageant_client_op_query(pco) == SSH2_AGENT_IDENTITIES_ANSWER)
  1814. return pco;
  1815. pageant_client_op_free(pco);
  1816. return NULL;
  1817. }
  1818. static PageantClientOp *pageant_request_keylist_extended(void)
  1819. {
  1820. PageantClientOp *pco = pageant_client_op_new();
  1821. put_byte(pco, SSH2_AGENTC_EXTENSION);
  1822. put_stringpl(pco, extension_names[EXT_LIST_EXTENDED]);
  1823. if (pageant_client_op_query(pco) == SSH_AGENT_SUCCESS)
  1824. return pco;
  1825. pageant_client_op_free(pco);
  1826. return NULL;
  1827. }
  1828. static KeyList *pageant_get_keylist(unsigned ssh_version)
  1829. {
  1830. PageantClientOp *pco;
  1831. bool list_is_extended = false;
  1832. if (ssh_version == 1) {
  1833. pco = pageant_request_keylist_1();
  1834. } else {
  1835. if ((pco = pageant_request_keylist_extended()) != NULL)
  1836. list_is_extended = true;
  1837. else
  1838. pco = pageant_request_keylist_2();
  1839. }
  1840. if (!pco)
  1841. return NULL;
  1842. KeyList *kl = snew(KeyList);
  1843. kl->nkeys = get_uint32(pco);
  1844. kl->keys = snewn(kl->nkeys, struct KeyListEntry);
  1845. kl->broken = false;
  1846. for (size_t i = 0; i < kl->nkeys && !get_err(pco); i++) {
  1847. if (ssh_version == 1) {
  1848. int bloblen = rsa_ssh1_public_blob_len(
  1849. make_ptrlen(get_ptr(pco), get_avail(pco)));
  1850. if (bloblen < 0) {
  1851. kl->broken = true;
  1852. bloblen = 0;
  1853. }
  1854. kl->keys[i].blob = get_data(pco, bloblen);
  1855. } else {
  1856. kl->keys[i].blob = get_string(pco);
  1857. }
  1858. kl->keys[i].comment = get_string(pco);
  1859. if (list_is_extended) {
  1860. ptrlen key_ext_info = get_string(pco);
  1861. BinarySource src[1];
  1862. BinarySource_BARE_INIT_PL(src, key_ext_info);
  1863. kl->keys[i].flags = get_uint32(src);
  1864. } else {
  1865. kl->keys[i].flags = 0;
  1866. }
  1867. }
  1868. if (get_err(pco))
  1869. kl->broken = true;
  1870. kl->raw_data = pco->buf;
  1871. pco->buf = NULL;
  1872. pageant_client_op_free(pco);
  1873. return kl;
  1874. }
  1875. int pageant_add_keyfile(Filename *filename, const char *passphrase,
  1876. char **retstr, bool add_encrypted)
  1877. {
  1878. RSAKey *rkey = NULL;
  1879. ssh2_userkey *skey = NULL;
  1880. bool needs_pass;
  1881. int ret;
  1882. int attempts;
  1883. char *comment;
  1884. const char *this_passphrase;
  1885. const char *error = NULL;
  1886. int type;
  1887. if (!passphrases) {
  1888. passphrases = newtree234(NULL);
  1889. }
  1890. *retstr = NULL;
  1891. type = key_type(filename);
  1892. if (type != SSH_KEYTYPE_SSH1 && type != SSH_KEYTYPE_SSH2) {
  1893. *retstr = dupprintf("Couldn't load this key (%s)",
  1894. key_type_to_str(type));
  1895. return PAGEANT_ACTION_FAILURE;
  1896. }
  1897. if (add_encrypted && type == SSH_KEYTYPE_SSH1) {
  1898. *retstr = dupprintf("Can't add SSH-1 keys in encrypted form");
  1899. return PAGEANT_ACTION_FAILURE;
  1900. }
  1901. /*
  1902. * See if the key is already loaded (in the primary Pageant,
  1903. * which may or may not be us).
  1904. */
  1905. {
  1906. strbuf *blob = strbuf_new();
  1907. KeyList *kl;
  1908. if (type == SSH_KEYTYPE_SSH1) {
  1909. if (!rsa1_loadpub_f(filename, BinarySink_UPCAST(blob),
  1910. NULL, &error)) {
  1911. *retstr = dupprintf("Couldn't load private key (%s)", error);
  1912. strbuf_free(blob);
  1913. return PAGEANT_ACTION_FAILURE;
  1914. }
  1915. kl = pageant_get_keylist(1);
  1916. } else {
  1917. if (!ppk_loadpub_f(filename, NULL, BinarySink_UPCAST(blob),
  1918. NULL, &error)) {
  1919. *retstr = dupprintf("Couldn't load private key (%s)", error);
  1920. strbuf_free(blob);
  1921. return PAGEANT_ACTION_FAILURE;
  1922. }
  1923. kl = pageant_get_keylist(2);
  1924. }
  1925. if (kl) {
  1926. if (kl->broken) {
  1927. *retstr = dupstr("Received broken key list from agent");
  1928. keylist_free(kl);
  1929. strbuf_free(blob);
  1930. return PAGEANT_ACTION_FAILURE;
  1931. }
  1932. for (size_t i = 0; i < kl->nkeys; i++) {
  1933. /*
  1934. * If the key already exists in the agent, we're done,
  1935. * except in the following special cases:
  1936. *
  1937. * It's encrypted in the agent, and we're being asked
  1938. * to add it unencrypted, in which case we still want
  1939. * to upload the unencrypted version to cause the key
  1940. * to become decrypted.
  1941. * (Rationale: if you know in advance you're going to
  1942. * want it, and don't want to be interrupted at an
  1943. * unpredictable moment to be asked for the
  1944. * passphrase.)
  1945. *
  1946. * The agent only has cleartext, and we're being asked
  1947. * to add it encrypted, in which case we'll add the
  1948. * encrypted form.
  1949. * (Rationale: if you might want to re-encrypt the key
  1950. * at some future point, but it happened to have been
  1951. * initially added in cleartext, perhaps by something
  1952. * other than Pageant.)
  1953. */
  1954. if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(blob),
  1955. kl->keys[i].blob)) {
  1956. bool have_unencrypted =
  1957. !(kl->keys[i].flags &
  1958. LIST_EXTENDED_FLAG_HAS_NO_CLEARTEXT_KEY);
  1959. bool have_encrypted =
  1960. (kl->keys[i].flags &
  1961. LIST_EXTENDED_FLAG_HAS_ENCRYPTED_KEY_FILE);
  1962. if ((have_unencrypted && !add_encrypted)
  1963. || (have_encrypted && add_encrypted)) {
  1964. /* Key is already present in the desired form;
  1965. * we can now leave. */
  1966. keylist_free(kl);
  1967. strbuf_free(blob);
  1968. return PAGEANT_ACTION_OK;
  1969. }
  1970. }
  1971. }
  1972. keylist_free(kl);
  1973. }
  1974. strbuf_free(blob);
  1975. }
  1976. if (add_encrypted) {
  1977. const char *load_error;
  1978. LoadedFile *lf = lf_load_keyfile(filename, &load_error);
  1979. if (!lf) {
  1980. *retstr = dupstr(load_error);
  1981. return PAGEANT_ACTION_FAILURE;
  1982. }
  1983. PageantClientOp *pco = pageant_client_op_new();
  1984. put_byte(pco, SSH2_AGENTC_EXTENSION);
  1985. put_stringpl(pco, extension_names[EXT_ADD_PPK]);
  1986. put_string(pco, lf->data, lf->len);
  1987. lf_free(lf);
  1988. unsigned reply = pageant_client_op_query(pco);
  1989. pageant_client_op_free(pco);
  1990. if (reply != SSH_AGENT_SUCCESS) {
  1991. if (reply == SSH_AGENT_FAILURE) {
  1992. /* The agent didn't understand the protocol extension
  1993. * at all. */
  1994. *retstr = dupstr("Agent doesn't support adding "
  1995. "encrypted keys");
  1996. } else {
  1997. *retstr = dupstr("The already running agent "
  1998. "refused to add the key.");
  1999. }
  2000. return PAGEANT_ACTION_FAILURE;
  2001. }
  2002. return PAGEANT_ACTION_OK;
  2003. }
  2004. error = NULL;
  2005. if (type == SSH_KEYTYPE_SSH1)
  2006. needs_pass = rsa1_encrypted_f(filename, &comment);
  2007. else
  2008. needs_pass = ppk_encrypted_f(filename, &comment);
  2009. attempts = 0;
  2010. if (type == SSH_KEYTYPE_SSH1)
  2011. rkey = snew(RSAKey);
  2012. /*
  2013. * Loop round repeatedly trying to load the key, until we either
  2014. * succeed, fail for some serious reason, or run out of
  2015. * passphrases to try.
  2016. */
  2017. while (1) {
  2018. if (needs_pass) {
  2019. /*
  2020. * If we've been given a passphrase on input, try using
  2021. * it. Otherwise, try one from our tree234 of previously
  2022. * useful passphrases.
  2023. */
  2024. if (passphrase) {
  2025. this_passphrase = (attempts == 0 ? passphrase : NULL);
  2026. } else {
  2027. this_passphrase = (const char *)index234(passphrases, attempts);
  2028. }
  2029. if (!this_passphrase) {
  2030. /*
  2031. * Run out of passphrases to try.
  2032. */
  2033. *retstr = comment;
  2034. sfree(rkey);
  2035. return PAGEANT_ACTION_NEED_PP;
  2036. }
  2037. } else
  2038. this_passphrase = "";
  2039. if (type == SSH_KEYTYPE_SSH1)
  2040. ret = rsa1_load_f(filename, rkey, this_passphrase, &error);
  2041. else {
  2042. skey = ppk_load_f(filename, this_passphrase, &error);
  2043. if (skey == SSH2_WRONG_PASSPHRASE)
  2044. ret = -1;
  2045. else if (!skey)
  2046. ret = 0;
  2047. else
  2048. ret = 1;
  2049. }
  2050. if (ret == 0) {
  2051. /*
  2052. * Failed to load the key file, for some reason other than
  2053. * a bad passphrase.
  2054. */
  2055. *retstr = dupstr(error);
  2056. sfree(rkey);
  2057. if (comment)
  2058. sfree(comment);
  2059. return PAGEANT_ACTION_FAILURE;
  2060. } else if (ret == 1) {
  2061. /*
  2062. * Successfully loaded the key file.
  2063. */
  2064. break;
  2065. } else {
  2066. /*
  2067. * Passphrase wasn't right; go round again.
  2068. */
  2069. attempts++;
  2070. }
  2071. }
  2072. /*
  2073. * If we get here, we've successfully loaded the key into
  2074. * rkey/skey, but not yet added it to the agent.
  2075. */
  2076. /*
  2077. * If the key was successfully decrypted, save the passphrase for
  2078. * use with other keys we try to load.
  2079. */
  2080. {
  2081. char *pp_copy = dupstr(this_passphrase);
  2082. if (addpos234(passphrases, pp_copy, 0) != pp_copy) {
  2083. /* No need; it was already there. */
  2084. smemclr(pp_copy, strlen(pp_copy));
  2085. sfree(pp_copy);
  2086. }
  2087. }
  2088. if (comment)
  2089. sfree(comment);
  2090. if (type == SSH_KEYTYPE_SSH1) {
  2091. PageantClientOp *pco = pageant_client_op_new();
  2092. put_byte(pco, SSH1_AGENTC_ADD_RSA_IDENTITY);
  2093. rsa_ssh1_private_blob_agent(BinarySink_UPCAST(pco), rkey);
  2094. put_stringz(pco, rkey->comment);
  2095. unsigned reply = pageant_client_op_query(pco);
  2096. pageant_client_op_free(pco);
  2097. freersakey(rkey);
  2098. sfree(rkey);
  2099. if (reply != SSH_AGENT_SUCCESS) {
  2100. *retstr = dupstr("The already running agent "
  2101. "refused to add the key.");
  2102. return PAGEANT_ACTION_FAILURE;
  2103. }
  2104. } else {
  2105. PageantClientOp *pco = pageant_client_op_new();
  2106. put_byte(pco, SSH2_AGENTC_ADD_IDENTITY);
  2107. put_stringz(pco, ssh_key_ssh_id(skey->key));
  2108. ssh_key_openssh_blob(skey->key, BinarySink_UPCAST(pco));
  2109. put_stringz(pco, skey->comment);
  2110. unsigned reply = pageant_client_op_query(pco);
  2111. pageant_client_op_free(pco);
  2112. sfree(skey->comment);
  2113. ssh_key_free(skey->key);
  2114. sfree(skey);
  2115. if (reply != SSH_AGENT_SUCCESS) {
  2116. *retstr = dupstr("The already running agent "
  2117. "refused to add the key.");
  2118. return PAGEANT_ACTION_FAILURE;
  2119. }
  2120. }
  2121. return PAGEANT_ACTION_OK;
  2122. }
  2123. int pageant_enum_keys(pageant_key_enum_fn_t callback, void *callback_ctx,
  2124. char **retstr)
  2125. {
  2126. KeyList *kl1 = NULL, *kl2 = NULL;
  2127. struct pageant_pubkey cbkey;
  2128. int toret = PAGEANT_ACTION_FAILURE;
  2129. kl1 = pageant_get_keylist(1);
  2130. if (kl1 && kl1->broken) {
  2131. *retstr = dupstr("Received broken SSH-1 key list from agent");
  2132. goto out;
  2133. }
  2134. kl2 = pageant_get_keylist(2);
  2135. if (kl2 && kl2->broken) {
  2136. *retstr = dupstr("Received broken SSH-2 key list from agent");
  2137. goto out;
  2138. }
  2139. if (kl1) {
  2140. for (size_t i = 0; i < kl1->nkeys; i++) {
  2141. cbkey.blob = strbuf_dup(kl1->keys[i].blob);
  2142. cbkey.comment = mkstr(kl1->keys[i].comment);
  2143. cbkey.ssh_version = 1;
  2144. /* Decode public blob into a key in order to fingerprint it */
  2145. RSAKey rkey;
  2146. memset(&rkey, 0, sizeof(rkey));
  2147. {
  2148. BinarySource src[1];
  2149. BinarySource_BARE_INIT_PL(src, kl1->keys[i].blob);
  2150. get_rsa_ssh1_pub(src, &rkey, RSA_SSH1_EXPONENT_FIRST);
  2151. if (get_err(src)) {
  2152. *retstr = dupstr(
  2153. "Received an invalid SSH-1 key from agent");
  2154. goto out;
  2155. }
  2156. }
  2157. char **fingerprints = rsa_ssh1_fake_all_fingerprints(&rkey);
  2158. freersakey(&rkey);
  2159. callback(callback_ctx, fingerprints, cbkey.comment,
  2160. kl1->keys[i].flags, &cbkey);
  2161. strbuf_free(cbkey.blob);
  2162. sfree(cbkey.comment);
  2163. ssh2_free_all_fingerprints(fingerprints);
  2164. }
  2165. }
  2166. if (kl2) {
  2167. for (size_t i = 0; i < kl2->nkeys; i++) {
  2168. cbkey.blob = strbuf_dup(kl2->keys[i].blob);
  2169. cbkey.comment = mkstr(kl2->keys[i].comment);
  2170. cbkey.ssh_version = 2;
  2171. char **fingerprints =
  2172. ssh2_all_fingerprints_for_blob(kl2->keys[i].blob);
  2173. callback(callback_ctx, fingerprints, cbkey.comment,
  2174. kl2->keys[i].flags, &cbkey);
  2175. ssh2_free_all_fingerprints(fingerprints);
  2176. sfree(cbkey.comment);
  2177. strbuf_free(cbkey.blob);
  2178. }
  2179. }
  2180. *retstr = NULL;
  2181. toret = PAGEANT_ACTION_OK;
  2182. out:
  2183. if (kl1)
  2184. keylist_free(kl1);
  2185. if (kl2)
  2186. keylist_free(kl2);
  2187. return toret;
  2188. }
  2189. int pageant_delete_key(struct pageant_pubkey *key, char **retstr)
  2190. {
  2191. PageantClientOp *pco = pageant_client_op_new();
  2192. if (key->ssh_version == 1) {
  2193. put_byte(pco, SSH1_AGENTC_REMOVE_RSA_IDENTITY);
  2194. put_data(pco, key->blob->s, key->blob->len);
  2195. } else {
  2196. put_byte(pco, SSH2_AGENTC_REMOVE_IDENTITY);
  2197. put_string(pco, key->blob->s, key->blob->len);
  2198. }
  2199. unsigned reply = pageant_client_op_query(pco);
  2200. pageant_client_op_free(pco);
  2201. if (reply != SSH_AGENT_SUCCESS) {
  2202. *retstr = dupstr("Agent failed to delete key");
  2203. return PAGEANT_ACTION_FAILURE;
  2204. } else {
  2205. *retstr = NULL;
  2206. return PAGEANT_ACTION_OK;
  2207. }
  2208. }
  2209. int pageant_delete_all_keys(char **retstr)
  2210. {
  2211. PageantClientOp *pco;
  2212. unsigned reply;
  2213. pco = pageant_client_op_new();
  2214. put_byte(pco, SSH2_AGENTC_REMOVE_ALL_IDENTITIES);
  2215. reply = pageant_client_op_query(pco);
  2216. pageant_client_op_free(pco);
  2217. if (reply != SSH_AGENT_SUCCESS) {
  2218. *retstr = dupstr("Agent failed to delete SSH-2 keys");
  2219. return PAGEANT_ACTION_FAILURE;
  2220. }
  2221. pco = pageant_client_op_new();
  2222. put_byte(pco, SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES);
  2223. reply = pageant_client_op_query(pco);
  2224. pageant_client_op_free(pco);
  2225. if (reply != SSH_AGENT_SUCCESS) {
  2226. *retstr = dupstr("Agent failed to delete SSH-1 keys");
  2227. return PAGEANT_ACTION_FAILURE;
  2228. }
  2229. *retstr = NULL;
  2230. return PAGEANT_ACTION_OK;
  2231. }
  2232. int pageant_reencrypt_key(struct pageant_pubkey *key, char **retstr)
  2233. {
  2234. PageantClientOp *pco = pageant_client_op_new();
  2235. if (key->ssh_version == 1) {
  2236. *retstr = dupstr("Can't re-encrypt an SSH-1 key");
  2237. pageant_client_op_free(pco);
  2238. return PAGEANT_ACTION_FAILURE;
  2239. } else {
  2240. put_byte(pco, SSH2_AGENTC_EXTENSION);
  2241. put_stringpl(pco, extension_names[EXT_REENCRYPT]);
  2242. put_string(pco, key->blob->s, key->blob->len);
  2243. }
  2244. unsigned reply = pageant_client_op_query(pco);
  2245. pageant_client_op_free(pco);
  2246. if (reply != SSH_AGENT_SUCCESS) {
  2247. if (reply == SSH_AGENT_FAILURE) {
  2248. /* The agent didn't understand the protocol extension at all. */
  2249. *retstr = dupstr("Agent doesn't support encrypted keys");
  2250. } else {
  2251. *retstr = dupstr("Agent failed to re-encrypt key");
  2252. }
  2253. return PAGEANT_ACTION_FAILURE;
  2254. } else {
  2255. *retstr = NULL;
  2256. return PAGEANT_ACTION_OK;
  2257. }
  2258. }
  2259. int pageant_reencrypt_all_keys(char **retstr)
  2260. {
  2261. PageantClientOp *pco = pageant_client_op_new();
  2262. put_byte(pco, SSH2_AGENTC_EXTENSION);
  2263. put_stringpl(pco, extension_names[EXT_REENCRYPT_ALL]);
  2264. unsigned reply = pageant_client_op_query(pco);
  2265. uint32_t failures = get_uint32(pco);
  2266. pageant_client_op_free(pco);
  2267. if (reply != SSH_AGENT_SUCCESS) {
  2268. if (reply == SSH_AGENT_FAILURE) {
  2269. /* The agent didn't understand the protocol extension at all. */
  2270. *retstr = dupstr("Agent doesn't support encrypted keys");
  2271. } else {
  2272. *retstr = dupstr("Agent failed to re-encrypt any keys");
  2273. }
  2274. return PAGEANT_ACTION_FAILURE;
  2275. } else if (failures == 1) {
  2276. /* special case for English grammar */
  2277. *retstr = dupstr("1 key remains unencrypted");
  2278. return PAGEANT_ACTION_WARNING;
  2279. } else if (failures > 0) {
  2280. *retstr = dupprintf("%"PRIu32" keys remain unencrypted", failures);
  2281. return PAGEANT_ACTION_WARNING;
  2282. } else {
  2283. *retstr = NULL;
  2284. return PAGEANT_ACTION_OK;
  2285. }
  2286. }
  2287. int pageant_sign(struct pageant_pubkey *key, ptrlen message, strbuf *out,
  2288. uint32_t flags, char **retstr)
  2289. {
  2290. PageantClientOp *pco = pageant_client_op_new();
  2291. put_byte(pco, SSH2_AGENTC_SIGN_REQUEST);
  2292. put_string(pco, key->blob->s, key->blob->len);
  2293. put_stringpl(pco, message);
  2294. put_uint32(pco, flags);
  2295. unsigned reply = pageant_client_op_query(pco);
  2296. ptrlen signature = get_string(pco);
  2297. if (reply == SSH2_AGENT_SIGN_RESPONSE && !get_err(pco)) {
  2298. *retstr = NULL;
  2299. put_datapl(out, signature);
  2300. pageant_client_op_free(pco);
  2301. return PAGEANT_ACTION_OK;
  2302. } else {
  2303. *retstr = dupstr("Agent failed to create signature");
  2304. pageant_client_op_free(pco);
  2305. return PAGEANT_ACTION_FAILURE;
  2306. }
  2307. }
  2308. struct pageant_pubkey *pageant_pubkey_copy(struct pageant_pubkey *orig)
  2309. {
  2310. struct pageant_pubkey *copy = snew(struct pageant_pubkey);
  2311. copy->blob = strbuf_new();
  2312. put_data(copy->blob, orig->blob->s, orig->blob->len);
  2313. copy->comment = orig->comment ? dupstr(orig->comment) : NULL;
  2314. copy->ssh_version = orig->ssh_version;
  2315. return copy;
  2316. }
  2317. void pageant_pubkey_free(struct pageant_pubkey *key)
  2318. {
  2319. sfree(key->comment);
  2320. strbuf_free(key->blob);
  2321. sfree(key);
  2322. }