pageant.c 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693
  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. signop_unlink(so);
  570. strbuf_free(so->data_to_sign);
  571. sfree(so);
  572. }
  573. static bool request_passphrase(PageantClient *pc, PageantPrivateKey *priv)
  574. {
  575. if (!priv->decryption_prompt_active) {
  576. assert(!gui_request_in_progress);
  577. bool created_dlg = pageant_client_ask_passphrase(
  578. pc, &priv->dlgid, priv->encrypted_key_comment);
  579. if (!created_dlg)
  580. return false;
  581. gui_request_in_progress = true;
  582. priv->decryption_prompt_active = true;
  583. }
  584. return true;
  585. }
  586. static void signop_coroutine(PageantAsyncOp *pao)
  587. {
  588. PageantSignOp *so = container_of(pao, PageantSignOp, pao);
  589. strbuf *response;
  590. crBegin(so->crLine);
  591. while (!so->priv->skey && gui_request_in_progress) {
  592. signop_link_to_pending_gui_request(so);
  593. crReturnV;
  594. signop_unlink(so);
  595. }
  596. if (!so->priv->skey) {
  597. assert(so->priv->encrypted_key_file);
  598. if (!request_passphrase(so->pao.info->pc, so->priv)) {
  599. response = strbuf_new();
  600. failure(so->pao.info->pc, so->pao.reqid, response,
  601. so->failure_type, "on-demand decryption could not "
  602. "prompt for a passphrase");
  603. goto respond;
  604. }
  605. signop_link_to_key(so);
  606. crReturnV;
  607. signop_unlink(so);
  608. }
  609. uint32_t supported_flags = ssh_key_supported_flags(so->priv->skey);
  610. if (so->flags & ~supported_flags) {
  611. /*
  612. * We MUST reject any message containing flags we don't
  613. * understand.
  614. */
  615. response = strbuf_new();
  616. failure(so->pao.info->pc, so->pao.reqid, response, so->failure_type,
  617. "unsupported flag bits 0x%08"PRIx32,
  618. so->flags & ~supported_flags);
  619. goto respond;
  620. }
  621. char *invalid = ssh_key_invalid(so->priv->skey, so->flags);
  622. if (invalid) {
  623. response = strbuf_new();
  624. failure(so->pao.info->pc, so->pao.reqid, response, so->failure_type,
  625. "key invalid: %s", invalid);
  626. sfree(invalid);
  627. goto respond;
  628. }
  629. strbuf *signature = strbuf_new();
  630. ssh_key_sign(so->priv->skey, ptrlen_from_strbuf(so->data_to_sign),
  631. so->flags, BinarySink_UPCAST(signature));
  632. response = strbuf_new();
  633. put_byte(response, SSH2_AGENT_SIGN_RESPONSE);
  634. put_stringsb(response, signature);
  635. respond:
  636. pageant_client_got_response(so->pao.info->pc, so->pao.reqid,
  637. ptrlen_from_strbuf(response));
  638. strbuf_free(response);
  639. pageant_async_op_unlink_and_free(&so->pao);
  640. crFinishFreedV;
  641. }
  642. static const PageantAsyncOpVtable signop_vtable = {
  643. .coroutine = signop_coroutine,
  644. .free = signop_free,
  645. };
  646. static void fail_requests_for_key(PageantPrivateKey *priv, const char *reason)
  647. {
  648. while (priv->blocked_requests.next != &priv->blocked_requests) {
  649. PageantSignOp *so = container_of(priv->blocked_requests.next,
  650. PageantSignOp, pkr);
  651. signop_unlink(so);
  652. strbuf *sb = strbuf_new();
  653. failure(so->pao.info->pc, so->pao.reqid, sb, so->failure_type,
  654. "%s", reason);
  655. pageant_client_got_response(so->pao.info->pc, so->pao.reqid,
  656. ptrlen_from_strbuf(sb));
  657. strbuf_free(sb);
  658. pageant_async_op_unlink_and_free(&so->pao);
  659. }
  660. }
  661. static void unblock_requests_for_key(PageantPrivateKey *priv)
  662. {
  663. for (PageantKeyRequestNode *pkr = priv->blocked_requests.next;
  664. pkr != &priv->blocked_requests; pkr = pkr->next) {
  665. PageantSignOp *so = container_of(pkr, PageantSignOp, pkr);
  666. queue_toplevel_callback(pageant_async_op_callback, &so->pao);
  667. }
  668. }
  669. static void unblock_pending_gui_requests(void)
  670. {
  671. for (PageantKeyRequestNode *pkr = requests_blocked_on_gui.next;
  672. pkr != &requests_blocked_on_gui; pkr = pkr->next) {
  673. PageantSignOp *so = container_of(pkr, PageantSignOp, pkr);
  674. queue_toplevel_callback(pageant_async_op_callback, &so->pao);
  675. }
  676. }
  677. void pageant_passphrase_request_success(PageantClientDialogId *dlgid,
  678. ptrlen passphrase)
  679. {
  680. PageantPrivateKey *priv = container_of(dlgid, PageantPrivateKey, dlgid);
  681. assert(gui_request_in_progress);
  682. gui_request_in_progress = false;
  683. priv->decryption_prompt_active = false;
  684. if (!priv->skey) {
  685. const char *error;
  686. BinarySource src[1];
  687. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(
  688. priv->encrypted_key_file));
  689. strbuf *ppsb = strbuf_dup_nm(passphrase);
  690. ssh2_userkey *skey = ppk_load_s(src, ppsb->s, &error);
  691. strbuf_free(ppsb);
  692. if (!skey) {
  693. fail_requests_for_key(priv, "unable to decrypt key");
  694. return;
  695. } else if (skey == SSH2_WRONG_PASSPHRASE) {
  696. /*
  697. * Find a PageantClient to use for another attempt at
  698. * request_passphrase.
  699. */
  700. PageantKeyRequestNode *pkr = priv->blocked_requests.next;
  701. if (pkr == &priv->blocked_requests) {
  702. /*
  703. * Special case: if all the requests have gone away at
  704. * this point, we need not bother putting up a request
  705. * at all any more.
  706. */
  707. return;
  708. }
  709. PageantSignOp *so = container_of(priv->blocked_requests.next,
  710. PageantSignOp, pkr);
  711. priv->decryption_prompt_active = false;
  712. if (!request_passphrase(so->pao.info->pc, so->priv)) {
  713. fail_requests_for_key(priv, "unable to continue creating "
  714. "passphrase prompts");
  715. }
  716. return;
  717. } else {
  718. priv->skey = skey->key;
  719. sfree(skey->comment);
  720. sfree(skey);
  721. keylist_update();
  722. }
  723. }
  724. unblock_requests_for_key(priv);
  725. unblock_pending_gui_requests();
  726. }
  727. void pageant_passphrase_request_refused(PageantClientDialogId *dlgid)
  728. {
  729. PageantPrivateKey *priv = container_of(dlgid, PageantPrivateKey, dlgid);
  730. assert(gui_request_in_progress);
  731. gui_request_in_progress = false;
  732. priv->decryption_prompt_active = false;
  733. fail_requests_for_key(priv, "user refused to supply passphrase");
  734. unblock_pending_gui_requests();
  735. }
  736. typedef struct PageantImmOp PageantImmOp;
  737. struct PageantImmOp {
  738. int crLine;
  739. strbuf *response;
  740. PageantAsyncOp pao;
  741. };
  742. static void immop_free(PageantAsyncOp *pao)
  743. {
  744. PageantImmOp *io = container_of(pao, PageantImmOp, pao);
  745. if (io->response)
  746. strbuf_free(io->response);
  747. sfree(io);
  748. }
  749. static void immop_coroutine(PageantAsyncOp *pao)
  750. {
  751. PageantImmOp *io = container_of(pao, PageantImmOp, pao);
  752. crBegin(io->crLine);
  753. if (0) crReturnV;
  754. pageant_client_got_response(io->pao.info->pc, io->pao.reqid,
  755. ptrlen_from_strbuf(io->response));
  756. pageant_async_op_unlink_and_free(&io->pao);
  757. crFinishFreedV;
  758. }
  759. static const PageantAsyncOpVtable immop_vtable = {
  760. .coroutine = immop_coroutine,
  761. .free = immop_free,
  762. };
  763. static bool reencrypt_key(PageantPublicKey *pub)
  764. {
  765. PageantPrivateKey *priv = pub_to_priv(pub);
  766. if (priv->sort.ssh_version != 2) {
  767. /*
  768. * We don't support storing SSH-1 keys in encrypted form at
  769. * all.
  770. */
  771. return false;
  772. }
  773. if (!priv->encrypted_key_file) {
  774. /*
  775. * We can't re-encrypt a key if it doesn't have an encrypted
  776. * form. (We could make one up, of course - but with what
  777. * passphrase that we could expect the user to know later?)
  778. */
  779. return false;
  780. }
  781. /* Only actually free priv->skey if it exists. But we return success
  782. * regardless, so that 'please ensure this key isn't stored
  783. * decrypted' is idempotent. */
  784. if (priv->skey) {
  785. ssh_key_free(priv->skey);
  786. priv->skey = NULL;
  787. }
  788. return true;
  789. }
  790. #define DECL_EXT_ENUM(id, name) id,
  791. enum Extension { KNOWN_EXTENSIONS(DECL_EXT_ENUM) EXT_UNKNOWN };
  792. #define DEF_EXT_NAMES(id, name) PTRLEN_DECL_LITERAL(name),
  793. static const ptrlen extension_names[] = { KNOWN_EXTENSIONS(DEF_EXT_NAMES) };
  794. static PageantAsyncOp *pageant_make_op(
  795. PageantClient *pc, PageantClientRequestId *reqid, ptrlen msgpl)
  796. {
  797. BinarySource msg[1];
  798. strbuf *sb = strbuf_new_nm();
  799. unsigned char failure_type = SSH_AGENT_FAILURE;
  800. int type;
  801. #define fail(...) failure(pc, reqid, sb, failure_type, __VA_ARGS__)
  802. BinarySource_BARE_INIT_PL(msg, msgpl);
  803. type = get_byte(msg);
  804. if (get_err(msg)) {
  805. fail("message contained no type code");
  806. goto responded;
  807. }
  808. switch (type) {
  809. case SSH1_AGENTC_REQUEST_RSA_IDENTITIES: {
  810. /*
  811. * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER.
  812. */
  813. pageant_client_log(pc, reqid,
  814. "request: SSH1_AGENTC_REQUEST_RSA_IDENTITIES");
  815. put_byte(sb, SSH1_AGENT_RSA_IDENTITIES_ANSWER);
  816. pageant_make_keylist1(BinarySink_UPCAST(sb));
  817. pageant_client_log(pc, reqid,
  818. "reply: SSH1_AGENT_RSA_IDENTITIES_ANSWER");
  819. if (!pc->suppress_logging) {
  820. int i;
  821. PageantPublicKey *pub;
  822. for (i = 0; NULL != (pub = pageant_nth_pubkey(1, i)); i++) {
  823. PageantPrivateKey *priv = pub_to_priv(pub);
  824. char *fingerprint = rsa_ssh1_fingerprint(priv->rkey);
  825. pageant_client_log(pc, reqid, "returned key: %s",
  826. fingerprint);
  827. sfree(fingerprint);
  828. }
  829. }
  830. break;
  831. }
  832. case SSH2_AGENTC_REQUEST_IDENTITIES: {
  833. /*
  834. * Reply with SSH2_AGENT_IDENTITIES_ANSWER.
  835. */
  836. pageant_client_log(pc, reqid,
  837. "request: SSH2_AGENTC_REQUEST_IDENTITIES");
  838. put_byte(sb, SSH2_AGENT_IDENTITIES_ANSWER);
  839. pageant_make_keylist2(BinarySink_UPCAST(sb));
  840. pageant_client_log(pc, reqid, "reply: SSH2_AGENT_IDENTITIES_ANSWER");
  841. if (!pc->suppress_logging) {
  842. int i;
  843. PageantPublicKey *pub;
  844. for (i = 0; NULL != (pub = pageant_nth_pubkey(2, i)); i++) {
  845. char *fingerprint = ssh2_double_fingerprint_blob(
  846. pub->sort.full_pub, SSH_FPTYPE_DEFAULT);
  847. pageant_client_log(pc, reqid, "returned key: %s %s",
  848. fingerprint, pub->comment);
  849. sfree(fingerprint);
  850. }
  851. }
  852. break;
  853. }
  854. case SSH1_AGENTC_RSA_CHALLENGE: {
  855. /*
  856. * Reply with either SSH1_AGENT_RSA_RESPONSE or
  857. * SSH_AGENT_FAILURE, depending on whether we have that key
  858. * or not.
  859. */
  860. RSAKey reqkey;
  861. PageantPublicKey *pub;
  862. PageantPrivateKey *priv;
  863. mp_int *challenge, *response;
  864. ptrlen session_id;
  865. unsigned response_type;
  866. unsigned char response_md5[16];
  867. int i;
  868. pageant_client_log(pc, reqid, "request: SSH1_AGENTC_RSA_CHALLENGE");
  869. response = NULL;
  870. memset(&reqkey, 0, sizeof(reqkey));
  871. get_rsa_ssh1_pub(msg, &reqkey, RSA_SSH1_EXPONENT_FIRST);
  872. challenge = get_mp_ssh1(msg);
  873. session_id = get_data(msg, 16);
  874. response_type = get_uint32(msg);
  875. if (get_err(msg)) {
  876. fail("unable to decode request");
  877. goto challenge1_cleanup;
  878. }
  879. if (response_type != 1) {
  880. fail("response type other than 1 not supported");
  881. goto challenge1_cleanup;
  882. }
  883. if (!pc->suppress_logging) {
  884. char *fingerprint;
  885. reqkey.comment = NULL;
  886. fingerprint = rsa_ssh1_fingerprint(&reqkey);
  887. pageant_client_log(pc, reqid, "requested key: %s", fingerprint);
  888. sfree(fingerprint);
  889. }
  890. if ((pub = findpubkey1(&reqkey)) == NULL) {
  891. fail("key not found");
  892. goto challenge1_cleanup;
  893. }
  894. priv = pub_to_priv(pub);
  895. response = rsa_ssh1_decrypt(challenge, priv->rkey);
  896. {
  897. ssh_hash *h = ssh_hash_new(&ssh_md5);
  898. for (i = 0; i < 32; i++)
  899. put_byte(h, mp_get_byte(response, 31 - i));
  900. put_datapl(h, session_id);
  901. ssh_hash_final(h, response_md5);
  902. }
  903. put_byte(sb, SSH1_AGENT_RSA_RESPONSE);
  904. put_data(sb, response_md5, 16);
  905. pageant_client_log(pc, reqid, "reply: SSH1_AGENT_RSA_RESPONSE");
  906. challenge1_cleanup:
  907. if (response)
  908. mp_free(response);
  909. mp_free(challenge);
  910. freersakey(&reqkey);
  911. break;
  912. }
  913. case SSH2_AGENTC_SIGN_REQUEST: {
  914. /*
  915. * Reply with either SSH2_AGENT_SIGN_RESPONSE or
  916. * SSH_AGENT_FAILURE, depending on whether we have that key
  917. * or not.
  918. */
  919. PageantPublicKey *pub;
  920. ptrlen keyblob, sigdata;
  921. uint32_t flags;
  922. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_SIGN_REQUEST");
  923. keyblob = get_string(msg);
  924. sigdata = get_string(msg);
  925. if (get_err(msg)) {
  926. fail("unable to decode request");
  927. goto responded;
  928. }
  929. /*
  930. * Later versions of the agent protocol added a flags word
  931. * on the end of the sign request. That hasn't always been
  932. * there, so we don't complain if we don't find it.
  933. *
  934. * get_uint32 will default to returning zero if no data is
  935. * available.
  936. */
  937. bool have_flags = false;
  938. flags = get_uint32(msg);
  939. if (!get_err(msg))
  940. have_flags = true;
  941. if (!pc->suppress_logging) {
  942. char *fingerprint = ssh2_double_fingerprint_blob(
  943. keyblob, SSH_FPTYPE_DEFAULT);
  944. pageant_client_log(pc, reqid, "requested key: %s", fingerprint);
  945. sfree(fingerprint);
  946. }
  947. if ((pub = findpubkey2(keyblob)) == NULL) {
  948. fail("key not found");
  949. goto responded;
  950. }
  951. if (have_flags)
  952. pageant_client_log(pc, reqid, "signature flags = 0x%08"PRIx32,
  953. flags);
  954. else
  955. pageant_client_log(pc, reqid, "no signature flags");
  956. strbuf_free(sb); /* no immediate response */
  957. PageantSignOp *so = snew(PageantSignOp);
  958. so->pao.vt = &signop_vtable;
  959. so->pao.info = pc->info;
  960. so->pao.cr.prev = pc->info->head.prev;
  961. so->pao.cr.next = &pc->info->head;
  962. so->pao.cr.prev->next = so->pao.cr.next->prev = &so->pao.cr;
  963. so->pao.reqid = reqid;
  964. so->priv = pub_to_priv(pub);
  965. so->pkr.prev = so->pkr.next = NULL;
  966. so->data_to_sign = strbuf_dup(sigdata);
  967. so->flags = flags;
  968. so->failure_type = failure_type;
  969. so->crLine = 0;
  970. return &so->pao;
  971. break;
  972. }
  973. case SSH1_AGENTC_ADD_RSA_IDENTITY: {
  974. /*
  975. * Add to the list and return SSH_AGENT_SUCCESS, or
  976. * SSH_AGENT_FAILURE if the key was malformed.
  977. */
  978. RSAKey *key;
  979. pageant_client_log(pc, reqid, "request: SSH1_AGENTC_ADD_RSA_IDENTITY");
  980. key = get_rsa_ssh1_priv_agent(msg);
  981. key->comment = mkstr(get_string(msg));
  982. if (get_err(msg)) {
  983. fail("unable to decode request");
  984. goto add1_cleanup;
  985. }
  986. if (!rsa_verify(key)) {
  987. fail("key is invalid");
  988. goto add1_cleanup;
  989. }
  990. if (!pc->suppress_logging) {
  991. char *fingerprint = rsa_ssh1_fingerprint(key);
  992. pageant_client_log(pc, reqid,
  993. "submitted key: %s", fingerprint);
  994. sfree(fingerprint);
  995. }
  996. if (pageant_add_ssh1_key(key)) {
  997. keylist_update();
  998. put_byte(sb, SSH_AGENT_SUCCESS);
  999. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1000. key = NULL; /* don't free it in cleanup */
  1001. } else {
  1002. fail("key already present");
  1003. }
  1004. add1_cleanup:
  1005. if (key) {
  1006. freersakey(key);
  1007. sfree(key);
  1008. }
  1009. break;
  1010. }
  1011. case SSH2_AGENTC_ADD_IDENTITY: {
  1012. /*
  1013. * Add to the list and return SSH_AGENT_SUCCESS, or
  1014. * SSH_AGENT_FAILURE if the key was malformed.
  1015. */
  1016. ssh2_userkey *key = NULL;
  1017. ptrlen algpl;
  1018. const ssh_keyalg *alg;
  1019. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_ADD_IDENTITY");
  1020. algpl = get_string(msg);
  1021. key = snew(ssh2_userkey);
  1022. key->key = NULL;
  1023. key->comment = NULL;
  1024. alg = find_pubkey_alg_len(algpl);
  1025. if (!alg) {
  1026. fail("algorithm unknown");
  1027. goto add2_cleanup;
  1028. }
  1029. key->key = ssh_key_new_priv_openssh(alg, msg);
  1030. if (!key->key) {
  1031. fail("key setup failed");
  1032. goto add2_cleanup;
  1033. }
  1034. key->comment = mkstr(get_string(msg));
  1035. if (get_err(msg)) {
  1036. fail("unable to decode request");
  1037. goto add2_cleanup;
  1038. }
  1039. if (!pc->suppress_logging) {
  1040. char *fingerprint = ssh2_fingerprint(key->key, SSH_FPTYPE_DEFAULT);
  1041. pageant_client_log(pc, reqid, "submitted key: %s %s",
  1042. fingerprint, key->comment);
  1043. sfree(fingerprint);
  1044. }
  1045. if (pageant_add_ssh2_key(key)) {
  1046. keylist_update();
  1047. put_byte(sb, SSH_AGENT_SUCCESS);
  1048. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1049. key = NULL; /* don't clean it up */
  1050. } else {
  1051. fail("key already present");
  1052. }
  1053. add2_cleanup:
  1054. if (key) {
  1055. if (key->key)
  1056. ssh_key_free(key->key);
  1057. if (key->comment)
  1058. sfree(key->comment);
  1059. sfree(key);
  1060. }
  1061. break;
  1062. }
  1063. case SSH1_AGENTC_REMOVE_RSA_IDENTITY: {
  1064. /*
  1065. * Remove from the list and return SSH_AGENT_SUCCESS, or
  1066. * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
  1067. * start with.
  1068. */
  1069. RSAKey reqkey;
  1070. PageantPublicKey *pub;
  1071. pageant_client_log(pc, reqid,
  1072. "request: SSH1_AGENTC_REMOVE_RSA_IDENTITY");
  1073. memset(&reqkey, 0, sizeof(reqkey));
  1074. get_rsa_ssh1_pub(msg, &reqkey, RSA_SSH1_EXPONENT_FIRST);
  1075. if (get_err(msg)) {
  1076. fail("unable to decode request");
  1077. freersakey(&reqkey);
  1078. goto responded;
  1079. }
  1080. if (!pc->suppress_logging) {
  1081. char *fingerprint;
  1082. reqkey.comment = NULL;
  1083. fingerprint = rsa_ssh1_fingerprint(&reqkey);
  1084. pageant_client_log(pc, reqid, "unwanted key: %s", fingerprint);
  1085. sfree(fingerprint);
  1086. }
  1087. pub = findpubkey1(&reqkey);
  1088. freersakey(&reqkey);
  1089. if (pub) {
  1090. pageant_client_log(pc, reqid, "found with comment: %s",
  1091. pub->comment);
  1092. del_pubkey(pub);
  1093. keylist_update();
  1094. pk_pub_free(pub);
  1095. put_byte(sb, SSH_AGENT_SUCCESS);
  1096. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1097. } else {
  1098. fail("key not found");
  1099. }
  1100. break;
  1101. }
  1102. case SSH2_AGENTC_REMOVE_IDENTITY: {
  1103. /*
  1104. * Remove from the list and return SSH_AGENT_SUCCESS, or
  1105. * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
  1106. * start with.
  1107. */
  1108. PageantPublicKey *pub;
  1109. ptrlen blob;
  1110. pageant_client_log(pc, reqid, "request: SSH2_AGENTC_REMOVE_IDENTITY");
  1111. blob = get_string(msg);
  1112. if (get_err(msg)) {
  1113. fail("unable to decode request");
  1114. goto responded;
  1115. }
  1116. if (!pc->suppress_logging) {
  1117. char *fingerprint = ssh2_double_fingerprint_blob(
  1118. blob, SSH_FPTYPE_DEFAULT);
  1119. pageant_client_log(pc, reqid, "unwanted key: %s", fingerprint);
  1120. sfree(fingerprint);
  1121. }
  1122. pub = findpubkey2(blob);
  1123. if (!pub) {
  1124. fail("key not found");
  1125. goto responded;
  1126. }
  1127. pageant_client_log(pc, reqid, "found with comment: %s", pub->comment);
  1128. del_pubkey(pub);
  1129. keylist_update();
  1130. pk_pub_free(pub);
  1131. put_byte(sb, SSH_AGENT_SUCCESS);
  1132. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1133. break;
  1134. }
  1135. case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES: {
  1136. /*
  1137. * Remove all SSH-1 keys. Always returns success.
  1138. */
  1139. pageant_client_log(pc, reqid,
  1140. "request: SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES");
  1141. remove_all_keys(1);
  1142. keylist_update();
  1143. put_byte(sb, SSH_AGENT_SUCCESS);
  1144. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1145. break;
  1146. }
  1147. case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: {
  1148. /*
  1149. * Remove all SSH-2 keys. Always returns success.
  1150. */
  1151. pageant_client_log(pc, reqid,
  1152. "request: SSH2_AGENTC_REMOVE_ALL_IDENTITIES");
  1153. remove_all_keys(2);
  1154. keylist_update();
  1155. put_byte(sb, SSH_AGENT_SUCCESS);
  1156. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1157. break;
  1158. }
  1159. case SSH2_AGENTC_EXTENSION: {
  1160. enum Extension exttype = EXT_UNKNOWN;
  1161. ptrlen extname = get_string(msg);
  1162. pageant_client_log(pc, reqid,
  1163. "request: SSH2_AGENTC_EXTENSION \"%.*s\"",
  1164. PTRLEN_PRINTF(extname));
  1165. for (size_t i = 0; i < lenof(extension_names); i++)
  1166. if (ptrlen_eq_ptrlen(extname, extension_names[i])) {
  1167. exttype = i;
  1168. /*
  1169. * For SSH_AGENTC_EXTENSION requests, the message
  1170. * code SSH_AGENT_FAILURE is reserved for "I don't
  1171. * recognise this extension name at all". For any
  1172. * other kind of failure while processing an
  1173. * extension we _do_ recognise, we must switch to
  1174. * returning a different failure code, with
  1175. * semantics "I understood the extension name, but
  1176. * something else went wrong".
  1177. */
  1178. failure_type = SSH_AGENT_EXTENSION_FAILURE;
  1179. break;
  1180. }
  1181. switch (exttype) {
  1182. case EXT_UNKNOWN:
  1183. fail("unrecognised extension name '%.*s'",
  1184. PTRLEN_PRINTF(extname));
  1185. break;
  1186. case EXT_QUERY:
  1187. /* Standard request to list the supported extensions. */
  1188. put_byte(sb, SSH_AGENT_SUCCESS);
  1189. for (size_t i = 0; i < lenof(extension_names); i++)
  1190. put_stringpl(sb, extension_names[i]);
  1191. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS + names");
  1192. break;
  1193. case EXT_ADD_PPK: {
  1194. ptrlen keyfile = get_string(msg);
  1195. if (get_err(msg)) {
  1196. fail("unable to decode request");
  1197. goto responded;
  1198. }
  1199. strbuf *base_pub = NULL;
  1200. strbuf *full_pub = NULL;
  1201. BinarySource src[1];
  1202. const char *error;
  1203. full_pub = strbuf_new();
  1204. char *comment;
  1205. BinarySource_BARE_INIT_PL(src, keyfile);
  1206. if (!ppk_loadpub_s(src, NULL, BinarySink_UPCAST(full_pub),
  1207. &comment, &error)) {
  1208. fail("failed to extract public key blob: %s", error);
  1209. goto add_ppk_cleanup;
  1210. }
  1211. if (!pc->suppress_logging) {
  1212. char *fingerprint = ssh2_double_fingerprint_blob(
  1213. ptrlen_from_strbuf(full_pub), SSH_FPTYPE_DEFAULT);
  1214. pageant_client_log(pc, reqid, "add-ppk: %s %s",
  1215. fingerprint, comment);
  1216. sfree(fingerprint);
  1217. }
  1218. BinarySource_BARE_INIT_PL(src, keyfile);
  1219. bool encrypted = ppk_encrypted_s(src, NULL);
  1220. if (!encrypted) {
  1221. /* If the key isn't encrypted, then we should just
  1222. * load and add it in the obvious way. */
  1223. BinarySource_BARE_INIT_PL(src, keyfile);
  1224. ssh2_userkey *skey = ppk_load_s(src, NULL, &error);
  1225. if (!skey) {
  1226. fail("failed to decode private key: %s", error);
  1227. } else if (pageant_add_ssh2_key(skey)) {
  1228. keylist_update();
  1229. put_byte(sb, SSH_AGENT_SUCCESS);
  1230. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS"
  1231. " (loaded unencrypted PPK)");
  1232. } else {
  1233. fail("key already present");
  1234. if (skey->key)
  1235. ssh_key_free(skey->key);
  1236. if (skey->comment)
  1237. sfree(skey->comment);
  1238. sfree(skey);
  1239. }
  1240. goto add_ppk_cleanup;
  1241. }
  1242. PageantPublicKeySort sort;
  1243. sort.priv.ssh_version = 2;
  1244. sort.full_pub = ptrlen_from_strbuf(full_pub);
  1245. base_pub = make_base_pub_2(&sort);
  1246. pageant_add_ssh2_key_encrypted(sort, comment, keyfile);
  1247. keylist_update();
  1248. put_byte(sb, SSH_AGENT_SUCCESS);
  1249. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1250. add_ppk_cleanup:
  1251. if (full_pub)
  1252. strbuf_free(full_pub);
  1253. if (base_pub)
  1254. strbuf_free(base_pub);
  1255. sfree(comment);
  1256. break;
  1257. }
  1258. case EXT_REENCRYPT: {
  1259. /*
  1260. * Re-encrypt a single key, in the sense of deleting
  1261. * its unencrypted copy, returning it to the state of
  1262. * only having the encrypted PPK form stored, so that
  1263. * the next attempt to use it will have to re-prompt
  1264. * for the passphrase.
  1265. */
  1266. ptrlen blob = get_string(msg);
  1267. if (get_err(msg)) {
  1268. fail("unable to decode request");
  1269. goto responded;
  1270. }
  1271. if (!pc->suppress_logging) {
  1272. char *fingerprint = ssh2_double_fingerprint_blob(
  1273. blob, SSH_FPTYPE_DEFAULT);
  1274. pageant_client_log(pc, reqid, "key to re-encrypt: %s",
  1275. fingerprint);
  1276. sfree(fingerprint);
  1277. }
  1278. PageantPublicKey *pub = findpubkey2(blob);
  1279. if (!pub) {
  1280. fail("key not found");
  1281. goto responded;
  1282. }
  1283. pageant_client_log(pc, reqid,
  1284. "found with comment: %s", pub->comment);
  1285. if (!reencrypt_key(pub)) {
  1286. fail("this key couldn't be re-encrypted");
  1287. goto responded;
  1288. }
  1289. keylist_update();
  1290. put_byte(sb, SSH_AGENT_SUCCESS);
  1291. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS");
  1292. break;
  1293. }
  1294. case EXT_REENCRYPT_ALL: {
  1295. /*
  1296. * Re-encrypt all keys that have an encrypted form
  1297. * stored. Usually, returns success, but with a uint32
  1298. * appended indicating how many keys remain
  1299. * unencrypted. The exception is if there is at least
  1300. * one key in the agent and _no_ key was successfully
  1301. * re-encrypted; in that situation we've done nothing,
  1302. * and the client didn't _want_ us to do nothing, so
  1303. * we return failure.
  1304. *
  1305. * (Rationale: the 'failure' message ought to be
  1306. * atomic, that is, you shouldn't return failure
  1307. * having made a state change.)
  1308. */
  1309. unsigned nfailures = 0, nsuccesses = 0;
  1310. PageantPublicKey *pub;
  1311. for (int i = 0; (pub = index234(pubkeytree, i)) != NULL; i++) {
  1312. if (reencrypt_key(pub))
  1313. nsuccesses++;
  1314. else
  1315. nfailures++;
  1316. }
  1317. if (nsuccesses == 0 && nfailures > 0) {
  1318. fail("no key could be re-encrypted");
  1319. } else {
  1320. keylist_update();
  1321. put_byte(sb, SSH_AGENT_SUCCESS);
  1322. put_uint32(sb, nfailures);
  1323. pageant_client_log(pc, reqid, "reply: SSH_AGENT_SUCCESS "
  1324. "(%u keys re-encrypted, %u failures)",
  1325. nsuccesses, nfailures);
  1326. }
  1327. break;
  1328. }
  1329. case EXT_LIST_EXTENDED: {
  1330. /*
  1331. * Return a key list like SSH2_AGENTC_REQUEST_IDENTITIES,
  1332. * except that each key is annotated with extra
  1333. * information such as whether it's currently encrypted.
  1334. *
  1335. * The return message type is AGENT_SUCCESS with auxiliary
  1336. * data, which is more like other extension messages. I
  1337. * think it would be confusing to reuse IDENTITIES_ANSWER
  1338. * for a reply message with an incompatible format.
  1339. */
  1340. put_byte(sb, SSH_AGENT_SUCCESS);
  1341. pageant_make_keylist_extended(BinarySink_UPCAST(sb));
  1342. pageant_client_log(pc, reqid,
  1343. "reply: SSH2_AGENT_SUCCESS + key list");
  1344. if (!pc->suppress_logging) {
  1345. int i;
  1346. PageantPublicKey *pub;
  1347. for (i = 0; NULL != (pub = pageant_nth_pubkey(2, i)); i++) {
  1348. char *fingerprint = ssh2_double_fingerprint_blob(
  1349. ptrlen_from_strbuf(pub->full_pub),
  1350. SSH_FPTYPE_DEFAULT);
  1351. pageant_client_log(pc, reqid, "returned key: %s %s",
  1352. fingerprint, pub->comment);
  1353. sfree(fingerprint);
  1354. }
  1355. }
  1356. break;
  1357. }
  1358. }
  1359. break;
  1360. }
  1361. default:
  1362. pageant_client_log(pc, reqid, "request: unknown message type %d",
  1363. type);
  1364. fail("unrecognised message");
  1365. break;
  1366. }
  1367. #undef fail
  1368. responded:;
  1369. PageantImmOp *io = snew(PageantImmOp);
  1370. io->pao.vt = &immop_vtable;
  1371. io->pao.info = pc->info;
  1372. io->pao.cr.prev = pc->info->head.prev;
  1373. io->pao.cr.next = &pc->info->head;
  1374. io->pao.cr.prev->next = io->pao.cr.next->prev = &io->pao.cr;
  1375. io->pao.reqid = reqid;
  1376. io->response = sb;
  1377. io->crLine = 0;
  1378. return &io->pao;
  1379. }
  1380. void pageant_handle_msg(PageantClient *pc, PageantClientRequestId *reqid,
  1381. ptrlen msgpl)
  1382. {
  1383. PageantAsyncOp *pao = pageant_make_op(pc, reqid, msgpl);
  1384. queue_toplevel_callback(pageant_async_op_callback, pao);
  1385. }
  1386. void pageant_init(void)
  1387. {
  1388. pageant_local = true;
  1389. pubkeytree = newtree234(pubkey_cmpfn);
  1390. privkeytree = newtree234(privkey_cmpfn);
  1391. }
  1392. static PageantPublicKey *pageant_nth_pubkey(int ssh_version, int i)
  1393. {
  1394. PageantPublicKey *pub = index234(
  1395. pubkeytree, find_first_pubkey_for_version(ssh_version) + i);
  1396. if (pub && pub->sort.priv.ssh_version == ssh_version)
  1397. return pub;
  1398. else
  1399. return NULL;
  1400. }
  1401. bool pageant_delete_nth_ssh1_key(int i)
  1402. {
  1403. PageantPublicKey *pub = del_pubkey_pos(
  1404. find_first_pubkey_for_version(1) + i);
  1405. if (!pub)
  1406. return false;
  1407. pk_pub_free(pub);
  1408. return true;
  1409. }
  1410. bool pageant_delete_nth_ssh2_key(int i)
  1411. {
  1412. PageantPublicKey *pub = del_pubkey_pos(
  1413. find_first_pubkey_for_version(2) + i);
  1414. if (!pub)
  1415. return false;
  1416. pk_pub_free(pub);
  1417. return true;
  1418. }
  1419. bool pageant_reencrypt_nth_ssh2_key(int i)
  1420. {
  1421. PageantPublicKey *pub = index234(
  1422. pubkeytree, find_first_pubkey_for_version(2) + i);
  1423. if (!pub)
  1424. return false;
  1425. return reencrypt_key(pub);
  1426. }
  1427. void pageant_delete_all(void)
  1428. {
  1429. remove_all_keys(1);
  1430. remove_all_keys(2);
  1431. }
  1432. void pageant_reencrypt_all(void)
  1433. {
  1434. PageantPublicKey *pub;
  1435. for (int i = 0; (pub = index234(pubkeytree, i)) != NULL; i++)
  1436. reencrypt_key(pub);
  1437. }
  1438. /* ----------------------------------------------------------------------
  1439. * The agent plug.
  1440. */
  1441. /*
  1442. * An extra coroutine macro, specific to this code which is consuming
  1443. * 'const char *data'.
  1444. */
  1445. #define crGetChar(c) do \
  1446. { \
  1447. while (len == 0) { \
  1448. *crLine = __LINE__; return; case __LINE__:; \
  1449. } \
  1450. len--; \
  1451. (c) = (unsigned char)*data++; \
  1452. } while (0)
  1453. struct pageant_conn_queued_response {
  1454. struct pageant_conn_queued_response *next, *prev;
  1455. size_t req_index; /* for indexing requests in log messages */
  1456. strbuf *sb;
  1457. PageantClientRequestId reqid;
  1458. };
  1459. struct pageant_conn_state {
  1460. Socket *connsock;
  1461. PageantListenerClient *plc;
  1462. unsigned char lenbuf[4], pktbuf[AGENT_MAX_MSGLEN];
  1463. unsigned len, got;
  1464. bool real_packet;
  1465. size_t conn_index; /* for indexing connections in log messages */
  1466. size_t req_index; /* for indexing requests in log messages */
  1467. int crLine; /* for coroutine in pageant_conn_receive */
  1468. struct pageant_conn_queued_response response_queue;
  1469. PageantClient pc;
  1470. Plug plug;
  1471. };
  1472. static void pageant_conn_closing(Plug *plug, PlugCloseType type,
  1473. const char *error_msg)
  1474. {
  1475. struct pageant_conn_state *pc = container_of(
  1476. plug, struct pageant_conn_state, plug);
  1477. if (type != PLUGCLOSE_NORMAL)
  1478. pageant_listener_client_log(pc->plc, "c#%"SIZEu": error: %s",
  1479. pc->conn_index, error_msg);
  1480. else
  1481. pageant_listener_client_log(pc->plc, "c#%"SIZEu": connection closed",
  1482. pc->conn_index);
  1483. sk_close(pc->connsock);
  1484. pageant_unregister_client(&pc->pc);
  1485. sfree(pc);
  1486. }
  1487. static void pageant_conn_sent(Plug *plug, size_t bufsize)
  1488. {
  1489. /* struct pageant_conn_state *pc = container_of(
  1490. plug, struct pageant_conn_state, plug); */
  1491. /*
  1492. * We do nothing here, because we expect that there won't be a
  1493. * need to throttle and unthrottle the connection to an agent -
  1494. * clients will typically not send many requests, and will wait
  1495. * until they receive each reply before sending a new request.
  1496. */
  1497. }
  1498. static void pageant_conn_log(PageantClient *pc, PageantClientRequestId *reqid,
  1499. const char *fmt, va_list ap)
  1500. {
  1501. struct pageant_conn_state *pcs =
  1502. container_of(pc, struct pageant_conn_state, pc);
  1503. struct pageant_conn_queued_response *qr =
  1504. container_of(reqid, struct pageant_conn_queued_response, reqid);
  1505. char *formatted = dupvprintf(fmt, ap);
  1506. pageant_listener_client_log(pcs->plc, "c#%"SIZEu",r#%"SIZEu": %s",
  1507. pcs->conn_index, qr->req_index, formatted);
  1508. sfree(formatted);
  1509. }
  1510. static void pageant_conn_got_response(
  1511. PageantClient *pc, PageantClientRequestId *reqid, ptrlen response)
  1512. {
  1513. struct pageant_conn_state *pcs =
  1514. container_of(pc, struct pageant_conn_state, pc);
  1515. struct pageant_conn_queued_response *qr =
  1516. container_of(reqid, struct pageant_conn_queued_response, reqid);
  1517. qr->sb = strbuf_new_nm();
  1518. put_stringpl(qr->sb, response);
  1519. while (pcs->response_queue.next != &pcs->response_queue &&
  1520. pcs->response_queue.next->sb) {
  1521. qr = pcs->response_queue.next;
  1522. sk_write(pcs->connsock, qr->sb->u, qr->sb->len);
  1523. qr->next->prev = qr->prev;
  1524. qr->prev->next = qr->next;
  1525. strbuf_free(qr->sb);
  1526. sfree(qr);
  1527. }
  1528. }
  1529. static bool pageant_conn_ask_passphrase(
  1530. PageantClient *pc, PageantClientDialogId *dlgid, const char *comment)
  1531. {
  1532. struct pageant_conn_state *pcs =
  1533. container_of(pc, struct pageant_conn_state, pc);
  1534. return pageant_listener_client_ask_passphrase(pcs->plc, dlgid, comment);
  1535. }
  1536. static const PageantClientVtable pageant_connection_clientvt = {
  1537. .log = pageant_conn_log,
  1538. .got_response = pageant_conn_got_response,
  1539. .ask_passphrase = pageant_conn_ask_passphrase,
  1540. };
  1541. static void pageant_conn_receive(
  1542. Plug *plug, int urgent, const char *data, size_t len)
  1543. {
  1544. struct pageant_conn_state *pc = container_of(
  1545. plug, struct pageant_conn_state, plug);
  1546. char c;
  1547. crBegin(pc->crLine);
  1548. while (len > 0) {
  1549. pc->got = 0;
  1550. while (pc->got < 4) {
  1551. crGetChar(c);
  1552. pc->lenbuf[pc->got++] = c;
  1553. }
  1554. pc->len = GET_32BIT_MSB_FIRST(pc->lenbuf);
  1555. pc->got = 0;
  1556. pc->real_packet = (pc->len < AGENT_MAX_MSGLEN-4);
  1557. {
  1558. struct pageant_conn_queued_response *qr =
  1559. snew(struct pageant_conn_queued_response);
  1560. qr->prev = pc->response_queue.prev;
  1561. qr->next = &pc->response_queue;
  1562. qr->prev->next = qr->next->prev = qr;
  1563. qr->sb = NULL;
  1564. qr->req_index = pc->req_index++;
  1565. }
  1566. if (!pc->real_packet) {
  1567. /*
  1568. * Send failure immediately, before consuming the packet
  1569. * data. That way we notify the client reasonably early
  1570. * even if the data channel has just started spewing
  1571. * nonsense.
  1572. */
  1573. pageant_client_log(&pc->pc, &pc->response_queue.prev->reqid,
  1574. "early reply: SSH_AGENT_FAILURE "
  1575. "(overlong message, length %u)", pc->len);
  1576. static const unsigned char failure[] = { SSH_AGENT_FAILURE };
  1577. pageant_conn_got_response(&pc->pc, &pc->response_queue.prev->reqid,
  1578. make_ptrlen(failure, lenof(failure)));
  1579. }
  1580. while (pc->got < pc->len) {
  1581. crGetChar(c);
  1582. if (pc->real_packet)
  1583. pc->pktbuf[pc->got] = c;
  1584. pc->got++;
  1585. }
  1586. if (pc->real_packet)
  1587. pageant_handle_msg(&pc->pc, &pc->response_queue.prev->reqid,
  1588. make_ptrlen(pc->pktbuf, pc->len));
  1589. }
  1590. crFinishV;
  1591. }
  1592. struct pageant_listen_state {
  1593. Socket *listensock;
  1594. PageantListenerClient *plc;
  1595. size_t conn_index; /* for indexing connections in log messages */
  1596. Plug plug;
  1597. };
  1598. static void pageant_listen_closing(Plug *plug, PlugCloseType type,
  1599. const char *error_msg)
  1600. {
  1601. struct pageant_listen_state *pl = container_of(
  1602. plug, struct pageant_listen_state, plug);
  1603. if (type != PLUGCLOSE_NORMAL)
  1604. pageant_listener_client_log(pl->plc, "listening socket: error: %s",
  1605. error_msg);
  1606. sk_close(pl->listensock);
  1607. pl->listensock = NULL;
  1608. }
  1609. static const PlugVtable pageant_connection_plugvt = {
  1610. .closing = pageant_conn_closing,
  1611. .receive = pageant_conn_receive,
  1612. .sent = pageant_conn_sent,
  1613. .log = nullplug_log,
  1614. };
  1615. static int pageant_listen_accepting(Plug *plug,
  1616. accept_fn_t constructor, accept_ctx_t ctx)
  1617. {
  1618. struct pageant_listen_state *pl = container_of(
  1619. plug, struct pageant_listen_state, plug);
  1620. struct pageant_conn_state *pc;
  1621. const char *err;
  1622. SocketEndpointInfo *peerinfo;
  1623. pc = snew(struct pageant_conn_state);
  1624. pc->plug.vt = &pageant_connection_plugvt;
  1625. pc->pc.vt = &pageant_connection_clientvt;
  1626. pc->plc = pl->plc;
  1627. pc->response_queue.next = pc->response_queue.prev = &pc->response_queue;
  1628. pc->conn_index = pl->conn_index++;
  1629. pc->req_index = 0;
  1630. pc->crLine = 0;
  1631. pc->connsock = constructor(ctx, &pc->plug);
  1632. if ((err = sk_socket_error(pc->connsock)) != NULL) {
  1633. sk_close(pc->connsock);
  1634. sfree(pc);
  1635. return 1;
  1636. }
  1637. sk_set_frozen(pc->connsock, false);
  1638. peerinfo = sk_peer_info(pc->connsock);
  1639. if (peerinfo && peerinfo->log_text) {
  1640. pageant_listener_client_log(pl->plc,
  1641. "c#%"SIZEu": new connection from %s",
  1642. pc->conn_index, peerinfo->log_text);
  1643. } else {
  1644. pageant_listener_client_log(pl->plc, "c#%"SIZEu": new connection",
  1645. pc->conn_index);
  1646. }
  1647. sk_free_endpoint_info(peerinfo);
  1648. pageant_register_client(&pc->pc);
  1649. return 0;
  1650. }
  1651. static const PlugVtable pageant_listener_plugvt = {
  1652. .closing = pageant_listen_closing,
  1653. .accepting = pageant_listen_accepting,
  1654. .log = nullplug_log,
  1655. };
  1656. struct pageant_listen_state *pageant_listener_new(
  1657. Plug **plug, PageantListenerClient *plc)
  1658. {
  1659. struct pageant_listen_state *pl = snew(struct pageant_listen_state);
  1660. pl->plug.vt = &pageant_listener_plugvt;
  1661. pl->plc = plc;
  1662. pl->listensock = NULL;
  1663. pl->conn_index = 0;
  1664. *plug = &pl->plug;
  1665. return pl;
  1666. }
  1667. void pageant_listener_got_socket(struct pageant_listen_state *pl, Socket *sock)
  1668. {
  1669. pl->listensock = sock;
  1670. }
  1671. void pageant_listener_free(struct pageant_listen_state *pl)
  1672. {
  1673. if (pl->listensock)
  1674. sk_close(pl->listensock);
  1675. sfree(pl);
  1676. }
  1677. /* ----------------------------------------------------------------------
  1678. * Code to perform agent operations either as a client, or within the
  1679. * same process as the running agent.
  1680. */
  1681. static tree234 *passphrases = NULL;
  1682. typedef struct PageantInternalClient {
  1683. strbuf *response;
  1684. bool got_response;
  1685. PageantClient pc;
  1686. } PageantInternalClient;
  1687. static void internal_client_got_response(
  1688. PageantClient *pc, PageantClientRequestId *reqid, ptrlen response)
  1689. {
  1690. PageantInternalClient *pic = container_of(pc, PageantInternalClient, pc);
  1691. strbuf_clear(pic->response);
  1692. put_datapl(pic->response, response);
  1693. pic->got_response = true;
  1694. }
  1695. static bool internal_client_ask_passphrase(
  1696. PageantClient *pc, PageantClientDialogId *dlgid, const char *comment)
  1697. {
  1698. /* No delaying operations are permitted in this mode */
  1699. return false;
  1700. }
  1701. static const PageantClientVtable internal_clientvt = {
  1702. .log = NULL,
  1703. .got_response = internal_client_got_response,
  1704. .ask_passphrase = internal_client_ask_passphrase,
  1705. };
  1706. typedef struct PageantClientOp {
  1707. strbuf *buf;
  1708. bool request_made;
  1709. BinarySink_DELEGATE_IMPLEMENTATION;
  1710. BinarySource_IMPLEMENTATION;
  1711. } PageantClientOp;
  1712. static PageantClientOp *pageant_client_op_new(void)
  1713. {
  1714. PageantClientOp *pco = snew(PageantClientOp);
  1715. pco->buf = strbuf_new_for_agent_query();
  1716. pco->request_made = false;
  1717. BinarySink_DELEGATE_INIT(pco, pco->buf);
  1718. BinarySource_INIT(pco, "", 0);
  1719. return pco;
  1720. }
  1721. static void pageant_client_op_free(PageantClientOp *pco)
  1722. {
  1723. if (pco->buf)
  1724. strbuf_free(pco->buf);
  1725. sfree(pco);
  1726. }
  1727. static unsigned pageant_client_op_query(PageantClientOp *pco)
  1728. {
  1729. /* Since we use the same strbuf for the request and the response,
  1730. * check by assertion that we aren't embarrassingly sending a
  1731. * previous response back to the agent */
  1732. assert(!pco->request_made);
  1733. pco->request_made = true;
  1734. if (!pageant_local) {
  1735. void *response_raw;
  1736. int resplen_raw;
  1737. agent_query_synchronous(pco->buf, &response_raw, &resplen_raw);
  1738. strbuf_clear(pco->buf);
  1739. put_data(pco->buf, response_raw, resplen_raw);
  1740. sfree(response_raw);
  1741. /* The data coming back from agent_query_synchronous will have
  1742. * its length field prepended. So we start by parsing it as an
  1743. * SSH-formatted string, and then reinitialise our
  1744. * BinarySource with the interior of that string. */
  1745. BinarySource_INIT_PL(pco, ptrlen_from_strbuf(pco->buf));
  1746. BinarySource_INIT_PL(pco, get_string(pco));
  1747. } else {
  1748. PageantInternalClient pic;
  1749. PageantClientRequestId reqid;
  1750. pic.pc.vt = &internal_clientvt;
  1751. pic.pc.suppress_logging = true;
  1752. pic.response = pco->buf;
  1753. pic.got_response = false;
  1754. pageant_register_client(&pic.pc);
  1755. assert(pco->buf->len > 4);
  1756. PageantAsyncOp *pao = pageant_make_op(
  1757. &pic.pc, &reqid, make_ptrlen(pco->buf->s + 4, pco->buf->len - 4));
  1758. while (!pic.got_response)
  1759. pageant_async_op_coroutine(pao);
  1760. pageant_unregister_client(&pic.pc);
  1761. BinarySource_INIT_PL(pco, ptrlen_from_strbuf(pco->buf));
  1762. }
  1763. /* Strip off and directly return the type byte, which every client
  1764. * will need, to save a boilerplate get_byte at each call site */
  1765. unsigned reply_type = get_byte(pco);
  1766. if (get_err(pco))
  1767. reply_type = 256; /* out-of-range code */
  1768. return reply_type;
  1769. }
  1770. /*
  1771. * After processing a list of filenames, we want to forget the
  1772. * passphrases.
  1773. */
  1774. void pageant_forget_passphrases(void)
  1775. {
  1776. if (!passphrases) /* in case we never set it up at all */
  1777. return;
  1778. while (count234(passphrases) > 0) {
  1779. char *pp = index234(passphrases, 0);
  1780. smemclr(pp, strlen(pp));
  1781. delpos234(passphrases, 0);
  1782. sfree(pp);
  1783. }
  1784. }
  1785. typedef struct KeyListEntry {
  1786. ptrlen blob, comment;
  1787. uint32_t flags;
  1788. } KeyListEntry;
  1789. typedef struct KeyList {
  1790. strbuf *raw_data;
  1791. KeyListEntry *keys;
  1792. size_t nkeys;
  1793. bool broken;
  1794. } KeyList;
  1795. static void keylist_free(KeyList *kl)
  1796. {
  1797. sfree(kl->keys);
  1798. strbuf_free(kl->raw_data);
  1799. sfree(kl);
  1800. }
  1801. static PageantClientOp *pageant_request_keylist_1(void)
  1802. {
  1803. PageantClientOp *pco = pageant_client_op_new();
  1804. put_byte(pco, SSH1_AGENTC_REQUEST_RSA_IDENTITIES);
  1805. if (pageant_client_op_query(pco) == SSH1_AGENT_RSA_IDENTITIES_ANSWER)
  1806. return pco;
  1807. pageant_client_op_free(pco);
  1808. return NULL;
  1809. }
  1810. static PageantClientOp *pageant_request_keylist_2(void)
  1811. {
  1812. PageantClientOp *pco = pageant_client_op_new();
  1813. put_byte(pco, SSH2_AGENTC_REQUEST_IDENTITIES);
  1814. if (pageant_client_op_query(pco) == SSH2_AGENT_IDENTITIES_ANSWER)
  1815. return pco;
  1816. pageant_client_op_free(pco);
  1817. return NULL;
  1818. }
  1819. static PageantClientOp *pageant_request_keylist_extended(void)
  1820. {
  1821. PageantClientOp *pco = pageant_client_op_new();
  1822. put_byte(pco, SSH2_AGENTC_EXTENSION);
  1823. put_stringpl(pco, extension_names[EXT_LIST_EXTENDED]);
  1824. if (pageant_client_op_query(pco) == SSH_AGENT_SUCCESS)
  1825. return pco;
  1826. pageant_client_op_free(pco);
  1827. return NULL;
  1828. }
  1829. static KeyList *pageant_get_keylist(unsigned ssh_version)
  1830. {
  1831. PageantClientOp *pco;
  1832. bool list_is_extended = false;
  1833. if (ssh_version == 1) {
  1834. pco = pageant_request_keylist_1();
  1835. } else {
  1836. if ((pco = pageant_request_keylist_extended()) != NULL)
  1837. list_is_extended = true;
  1838. else
  1839. pco = pageant_request_keylist_2();
  1840. }
  1841. if (!pco)
  1842. return NULL;
  1843. KeyList *kl = snew(KeyList);
  1844. kl->nkeys = get_uint32(pco);
  1845. kl->keys = snewn(kl->nkeys, struct KeyListEntry);
  1846. kl->broken = false;
  1847. for (size_t i = 0; i < kl->nkeys && !get_err(pco); i++) {
  1848. if (ssh_version == 1) {
  1849. int bloblen = rsa_ssh1_public_blob_len(
  1850. make_ptrlen(get_ptr(pco), get_avail(pco)));
  1851. if (bloblen < 0) {
  1852. kl->broken = true;
  1853. bloblen = 0;
  1854. }
  1855. kl->keys[i].blob = get_data(pco, bloblen);
  1856. } else {
  1857. kl->keys[i].blob = get_string(pco);
  1858. }
  1859. kl->keys[i].comment = get_string(pco);
  1860. if (list_is_extended) {
  1861. ptrlen key_ext_info = get_string(pco);
  1862. BinarySource src[1];
  1863. BinarySource_BARE_INIT_PL(src, key_ext_info);
  1864. kl->keys[i].flags = get_uint32(src);
  1865. } else {
  1866. kl->keys[i].flags = 0;
  1867. }
  1868. }
  1869. if (get_err(pco))
  1870. kl->broken = true;
  1871. kl->raw_data = pco->buf;
  1872. pco->buf = NULL;
  1873. pageant_client_op_free(pco);
  1874. return kl;
  1875. }
  1876. int pageant_add_keyfile(Filename *filename, const char *passphrase,
  1877. char **retstr, bool add_encrypted)
  1878. {
  1879. RSAKey *rkey = NULL;
  1880. ssh2_userkey *skey = NULL;
  1881. bool needs_pass;
  1882. int ret;
  1883. int attempts;
  1884. char *comment;
  1885. const char *this_passphrase;
  1886. const char *error = NULL;
  1887. int type;
  1888. if (!passphrases) {
  1889. passphrases = newtree234(NULL);
  1890. }
  1891. *retstr = NULL;
  1892. type = key_type(filename);
  1893. if (type != SSH_KEYTYPE_SSH1 && type != SSH_KEYTYPE_SSH2) {
  1894. *retstr = dupprintf("Couldn't load this key (%s)",
  1895. key_type_to_str(type));
  1896. return PAGEANT_ACTION_FAILURE;
  1897. }
  1898. if (add_encrypted && type == SSH_KEYTYPE_SSH1) {
  1899. *retstr = dupprintf("Can't add SSH-1 keys in encrypted form");
  1900. return PAGEANT_ACTION_FAILURE;
  1901. }
  1902. /*
  1903. * See if the key is already loaded (in the primary Pageant,
  1904. * which may or may not be us).
  1905. */
  1906. {
  1907. strbuf *blob = strbuf_new();
  1908. KeyList *kl;
  1909. if (type == SSH_KEYTYPE_SSH1) {
  1910. if (!rsa1_loadpub_f(filename, BinarySink_UPCAST(blob),
  1911. NULL, &error)) {
  1912. *retstr = dupprintf("Couldn't load private key (%s)", error);
  1913. strbuf_free(blob);
  1914. return PAGEANT_ACTION_FAILURE;
  1915. }
  1916. kl = pageant_get_keylist(1);
  1917. } else {
  1918. if (!ppk_loadpub_f(filename, NULL, BinarySink_UPCAST(blob),
  1919. NULL, &error)) {
  1920. *retstr = dupprintf("Couldn't load private key (%s)", error);
  1921. strbuf_free(blob);
  1922. return PAGEANT_ACTION_FAILURE;
  1923. }
  1924. kl = pageant_get_keylist(2);
  1925. }
  1926. if (kl) {
  1927. if (kl->broken) {
  1928. *retstr = dupstr("Received broken key list from agent");
  1929. keylist_free(kl);
  1930. strbuf_free(blob);
  1931. return PAGEANT_ACTION_FAILURE;
  1932. }
  1933. for (size_t i = 0; i < kl->nkeys; i++) {
  1934. /*
  1935. * If the key already exists in the agent, we're done,
  1936. * except in the following special cases:
  1937. *
  1938. * It's encrypted in the agent, and we're being asked
  1939. * to add it unencrypted, in which case we still want
  1940. * to upload the unencrypted version to cause the key
  1941. * to become decrypted.
  1942. * (Rationale: if you know in advance you're going to
  1943. * want it, and don't want to be interrupted at an
  1944. * unpredictable moment to be asked for the
  1945. * passphrase.)
  1946. *
  1947. * The agent only has cleartext, and we're being asked
  1948. * to add it encrypted, in which case we'll add the
  1949. * encrypted form.
  1950. * (Rationale: if you might want to re-encrypt the key
  1951. * at some future point, but it happened to have been
  1952. * initially added in cleartext, perhaps by something
  1953. * other than Pageant.)
  1954. */
  1955. if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(blob),
  1956. kl->keys[i].blob)) {
  1957. bool have_unencrypted =
  1958. !(kl->keys[i].flags &
  1959. LIST_EXTENDED_FLAG_HAS_NO_CLEARTEXT_KEY);
  1960. bool have_encrypted =
  1961. (kl->keys[i].flags &
  1962. LIST_EXTENDED_FLAG_HAS_ENCRYPTED_KEY_FILE);
  1963. if ((have_unencrypted && !add_encrypted)
  1964. || (have_encrypted && add_encrypted)) {
  1965. /* Key is already present in the desired form;
  1966. * we can now leave. */
  1967. keylist_free(kl);
  1968. strbuf_free(blob);
  1969. return PAGEANT_ACTION_OK;
  1970. }
  1971. }
  1972. }
  1973. keylist_free(kl);
  1974. }
  1975. strbuf_free(blob);
  1976. }
  1977. if (add_encrypted) {
  1978. const char *load_error;
  1979. LoadedFile *lf = lf_load_keyfile(filename, &load_error);
  1980. if (!lf) {
  1981. *retstr = dupstr(load_error);
  1982. return PAGEANT_ACTION_FAILURE;
  1983. }
  1984. PageantClientOp *pco = pageant_client_op_new();
  1985. put_byte(pco, SSH2_AGENTC_EXTENSION);
  1986. put_stringpl(pco, extension_names[EXT_ADD_PPK]);
  1987. put_string(pco, lf->data, lf->len);
  1988. lf_free(lf);
  1989. unsigned reply = pageant_client_op_query(pco);
  1990. pageant_client_op_free(pco);
  1991. if (reply != SSH_AGENT_SUCCESS) {
  1992. if (reply == SSH_AGENT_FAILURE) {
  1993. /* The agent didn't understand the protocol extension
  1994. * at all. */
  1995. *retstr = dupstr("Agent doesn't support adding "
  1996. "encrypted keys");
  1997. } else {
  1998. *retstr = dupstr("The already running agent "
  1999. "refused to add the key.");
  2000. }
  2001. return PAGEANT_ACTION_FAILURE;
  2002. }
  2003. return PAGEANT_ACTION_OK;
  2004. }
  2005. error = NULL;
  2006. if (type == SSH_KEYTYPE_SSH1)
  2007. needs_pass = rsa1_encrypted_f(filename, &comment);
  2008. else
  2009. needs_pass = ppk_encrypted_f(filename, &comment);
  2010. attempts = 0;
  2011. if (type == SSH_KEYTYPE_SSH1)
  2012. rkey = snew(RSAKey);
  2013. /*
  2014. * Loop round repeatedly trying to load the key, until we either
  2015. * succeed, fail for some serious reason, or run out of
  2016. * passphrases to try.
  2017. */
  2018. while (1) {
  2019. if (needs_pass) {
  2020. /*
  2021. * If we've been given a passphrase on input, try using
  2022. * it. Otherwise, try one from our tree234 of previously
  2023. * useful passphrases.
  2024. */
  2025. if (passphrase) {
  2026. this_passphrase = (attempts == 0 ? passphrase : NULL);
  2027. } else {
  2028. this_passphrase = (const char *)index234(passphrases, attempts);
  2029. }
  2030. if (!this_passphrase) {
  2031. /*
  2032. * Run out of passphrases to try.
  2033. */
  2034. *retstr = comment;
  2035. sfree(rkey);
  2036. return PAGEANT_ACTION_NEED_PP;
  2037. }
  2038. } else
  2039. this_passphrase = "";
  2040. if (type == SSH_KEYTYPE_SSH1)
  2041. ret = rsa1_load_f(filename, rkey, this_passphrase, &error);
  2042. else {
  2043. skey = ppk_load_f(filename, this_passphrase, &error);
  2044. if (skey == SSH2_WRONG_PASSPHRASE)
  2045. ret = -1;
  2046. else if (!skey)
  2047. ret = 0;
  2048. else
  2049. ret = 1;
  2050. }
  2051. if (ret == 0) {
  2052. /*
  2053. * Failed to load the key file, for some reason other than
  2054. * a bad passphrase.
  2055. */
  2056. *retstr = dupstr(error);
  2057. sfree(rkey);
  2058. if (comment)
  2059. sfree(comment);
  2060. return PAGEANT_ACTION_FAILURE;
  2061. } else if (ret == 1) {
  2062. /*
  2063. * Successfully loaded the key file.
  2064. */
  2065. break;
  2066. } else {
  2067. /*
  2068. * Passphrase wasn't right; go round again.
  2069. */
  2070. attempts++;
  2071. }
  2072. }
  2073. /*
  2074. * If we get here, we've successfully loaded the key into
  2075. * rkey/skey, but not yet added it to the agent.
  2076. */
  2077. /*
  2078. * If the key was successfully decrypted, save the passphrase for
  2079. * use with other keys we try to load.
  2080. */
  2081. {
  2082. char *pp_copy = dupstr(this_passphrase);
  2083. if (addpos234(passphrases, pp_copy, 0) != pp_copy) {
  2084. /* No need; it was already there. */
  2085. smemclr(pp_copy, strlen(pp_copy));
  2086. sfree(pp_copy);
  2087. }
  2088. }
  2089. if (comment)
  2090. sfree(comment);
  2091. if (type == SSH_KEYTYPE_SSH1) {
  2092. PageantClientOp *pco = pageant_client_op_new();
  2093. put_byte(pco, SSH1_AGENTC_ADD_RSA_IDENTITY);
  2094. rsa_ssh1_private_blob_agent(BinarySink_UPCAST(pco), rkey);
  2095. put_stringz(pco, rkey->comment);
  2096. unsigned reply = pageant_client_op_query(pco);
  2097. pageant_client_op_free(pco);
  2098. freersakey(rkey);
  2099. sfree(rkey);
  2100. if (reply != SSH_AGENT_SUCCESS) {
  2101. *retstr = dupstr("The already running agent "
  2102. "refused to add the key.");
  2103. return PAGEANT_ACTION_FAILURE;
  2104. }
  2105. } else {
  2106. PageantClientOp *pco = pageant_client_op_new();
  2107. put_byte(pco, SSH2_AGENTC_ADD_IDENTITY);
  2108. put_stringz(pco, ssh_key_ssh_id(skey->key));
  2109. ssh_key_openssh_blob(skey->key, BinarySink_UPCAST(pco));
  2110. put_stringz(pco, skey->comment);
  2111. unsigned reply = pageant_client_op_query(pco);
  2112. pageant_client_op_free(pco);
  2113. sfree(skey->comment);
  2114. ssh_key_free(skey->key);
  2115. sfree(skey);
  2116. if (reply != SSH_AGENT_SUCCESS) {
  2117. *retstr = dupstr("The already running agent "
  2118. "refused to add the key.");
  2119. return PAGEANT_ACTION_FAILURE;
  2120. }
  2121. }
  2122. return PAGEANT_ACTION_OK;
  2123. }
  2124. int pageant_enum_keys(pageant_key_enum_fn_t callback, void *callback_ctx,
  2125. char **retstr)
  2126. {
  2127. KeyList *kl1 = NULL, *kl2 = NULL;
  2128. struct pageant_pubkey cbkey;
  2129. int toret = PAGEANT_ACTION_FAILURE;
  2130. kl1 = pageant_get_keylist(1);
  2131. if (kl1 && kl1->broken) {
  2132. *retstr = dupstr("Received broken SSH-1 key list from agent");
  2133. goto out;
  2134. }
  2135. kl2 = pageant_get_keylist(2);
  2136. if (kl2 && kl2->broken) {
  2137. *retstr = dupstr("Received broken SSH-2 key list from agent");
  2138. goto out;
  2139. }
  2140. if (kl1) {
  2141. for (size_t i = 0; i < kl1->nkeys; i++) {
  2142. cbkey.blob = strbuf_dup(kl1->keys[i].blob);
  2143. cbkey.comment = mkstr(kl1->keys[i].comment);
  2144. cbkey.ssh_version = 1;
  2145. /* Decode public blob into a key in order to fingerprint it */
  2146. RSAKey rkey;
  2147. memset(&rkey, 0, sizeof(rkey));
  2148. {
  2149. BinarySource src[1];
  2150. BinarySource_BARE_INIT_PL(src, kl1->keys[i].blob);
  2151. get_rsa_ssh1_pub(src, &rkey, RSA_SSH1_EXPONENT_FIRST);
  2152. if (get_err(src)) {
  2153. *retstr = dupstr(
  2154. "Received an invalid SSH-1 key from agent");
  2155. goto out;
  2156. }
  2157. }
  2158. char **fingerprints = rsa_ssh1_fake_all_fingerprints(&rkey);
  2159. freersakey(&rkey);
  2160. callback(callback_ctx, fingerprints, cbkey.comment,
  2161. kl1->keys[i].flags, &cbkey);
  2162. strbuf_free(cbkey.blob);
  2163. sfree(cbkey.comment);
  2164. ssh2_free_all_fingerprints(fingerprints);
  2165. }
  2166. }
  2167. if (kl2) {
  2168. for (size_t i = 0; i < kl2->nkeys; i++) {
  2169. cbkey.blob = strbuf_dup(kl2->keys[i].blob);
  2170. cbkey.comment = mkstr(kl2->keys[i].comment);
  2171. cbkey.ssh_version = 2;
  2172. char **fingerprints =
  2173. ssh2_all_fingerprints_for_blob(kl2->keys[i].blob);
  2174. callback(callback_ctx, fingerprints, cbkey.comment,
  2175. kl2->keys[i].flags, &cbkey);
  2176. ssh2_free_all_fingerprints(fingerprints);
  2177. sfree(cbkey.comment);
  2178. strbuf_free(cbkey.blob);
  2179. }
  2180. }
  2181. *retstr = NULL;
  2182. toret = PAGEANT_ACTION_OK;
  2183. out:
  2184. if (kl1)
  2185. keylist_free(kl1);
  2186. if (kl2)
  2187. keylist_free(kl2);
  2188. return toret;
  2189. }
  2190. int pageant_delete_key(struct pageant_pubkey *key, char **retstr)
  2191. {
  2192. PageantClientOp *pco = pageant_client_op_new();
  2193. if (key->ssh_version == 1) {
  2194. put_byte(pco, SSH1_AGENTC_REMOVE_RSA_IDENTITY);
  2195. put_data(pco, key->blob->s, key->blob->len);
  2196. } else {
  2197. put_byte(pco, SSH2_AGENTC_REMOVE_IDENTITY);
  2198. put_string(pco, key->blob->s, key->blob->len);
  2199. }
  2200. unsigned reply = pageant_client_op_query(pco);
  2201. pageant_client_op_free(pco);
  2202. if (reply != SSH_AGENT_SUCCESS) {
  2203. *retstr = dupstr("Agent failed to delete key");
  2204. return PAGEANT_ACTION_FAILURE;
  2205. } else {
  2206. *retstr = NULL;
  2207. return PAGEANT_ACTION_OK;
  2208. }
  2209. }
  2210. int pageant_delete_all_keys(char **retstr)
  2211. {
  2212. PageantClientOp *pco;
  2213. unsigned reply;
  2214. pco = pageant_client_op_new();
  2215. put_byte(pco, SSH2_AGENTC_REMOVE_ALL_IDENTITIES);
  2216. reply = pageant_client_op_query(pco);
  2217. pageant_client_op_free(pco);
  2218. if (reply != SSH_AGENT_SUCCESS) {
  2219. *retstr = dupstr("Agent failed to delete SSH-2 keys");
  2220. return PAGEANT_ACTION_FAILURE;
  2221. }
  2222. pco = pageant_client_op_new();
  2223. put_byte(pco, SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES);
  2224. reply = pageant_client_op_query(pco);
  2225. pageant_client_op_free(pco);
  2226. if (reply != SSH_AGENT_SUCCESS) {
  2227. *retstr = dupstr("Agent failed to delete SSH-1 keys");
  2228. return PAGEANT_ACTION_FAILURE;
  2229. }
  2230. *retstr = NULL;
  2231. return PAGEANT_ACTION_OK;
  2232. }
  2233. int pageant_reencrypt_key(struct pageant_pubkey *key, char **retstr)
  2234. {
  2235. PageantClientOp *pco = pageant_client_op_new();
  2236. if (key->ssh_version == 1) {
  2237. *retstr = dupstr("Can't re-encrypt an SSH-1 key");
  2238. pageant_client_op_free(pco);
  2239. return PAGEANT_ACTION_FAILURE;
  2240. } else {
  2241. put_byte(pco, SSH2_AGENTC_EXTENSION);
  2242. put_stringpl(pco, extension_names[EXT_REENCRYPT]);
  2243. put_string(pco, key->blob->s, key->blob->len);
  2244. }
  2245. unsigned reply = pageant_client_op_query(pco);
  2246. pageant_client_op_free(pco);
  2247. if (reply != SSH_AGENT_SUCCESS) {
  2248. if (reply == SSH_AGENT_FAILURE) {
  2249. /* The agent didn't understand the protocol extension at all. */
  2250. *retstr = dupstr("Agent doesn't support encrypted keys");
  2251. } else {
  2252. *retstr = dupstr("Agent failed to re-encrypt key");
  2253. }
  2254. return PAGEANT_ACTION_FAILURE;
  2255. } else {
  2256. *retstr = NULL;
  2257. return PAGEANT_ACTION_OK;
  2258. }
  2259. }
  2260. int pageant_reencrypt_all_keys(char **retstr)
  2261. {
  2262. PageantClientOp *pco = pageant_client_op_new();
  2263. put_byte(pco, SSH2_AGENTC_EXTENSION);
  2264. put_stringpl(pco, extension_names[EXT_REENCRYPT_ALL]);
  2265. unsigned reply = pageant_client_op_query(pco);
  2266. uint32_t failures = get_uint32(pco);
  2267. pageant_client_op_free(pco);
  2268. if (reply != SSH_AGENT_SUCCESS) {
  2269. if (reply == SSH_AGENT_FAILURE) {
  2270. /* The agent didn't understand the protocol extension at all. */
  2271. *retstr = dupstr("Agent doesn't support encrypted keys");
  2272. } else {
  2273. *retstr = dupstr("Agent failed to re-encrypt any keys");
  2274. }
  2275. return PAGEANT_ACTION_FAILURE;
  2276. } else if (failures == 1) {
  2277. /* special case for English grammar */
  2278. *retstr = dupstr("1 key remains unencrypted");
  2279. return PAGEANT_ACTION_WARNING;
  2280. } else if (failures > 0) {
  2281. *retstr = dupprintf("%"PRIu32" keys remain unencrypted", failures);
  2282. return PAGEANT_ACTION_WARNING;
  2283. } else {
  2284. *retstr = NULL;
  2285. return PAGEANT_ACTION_OK;
  2286. }
  2287. }
  2288. int pageant_sign(struct pageant_pubkey *key, ptrlen message, strbuf *out,
  2289. uint32_t flags, char **retstr)
  2290. {
  2291. PageantClientOp *pco = pageant_client_op_new();
  2292. put_byte(pco, SSH2_AGENTC_SIGN_REQUEST);
  2293. put_string(pco, key->blob->s, key->blob->len);
  2294. put_stringpl(pco, message);
  2295. put_uint32(pco, flags);
  2296. unsigned reply = pageant_client_op_query(pco);
  2297. ptrlen signature = get_string(pco);
  2298. if (reply == SSH2_AGENT_SIGN_RESPONSE && !get_err(pco)) {
  2299. *retstr = NULL;
  2300. put_datapl(out, signature);
  2301. pageant_client_op_free(pco);
  2302. return PAGEANT_ACTION_OK;
  2303. } else {
  2304. *retstr = dupstr("Agent failed to create signature");
  2305. pageant_client_op_free(pco);
  2306. return PAGEANT_ACTION_FAILURE;
  2307. }
  2308. }
  2309. struct pageant_pubkey *pageant_pubkey_copy(struct pageant_pubkey *orig)
  2310. {
  2311. struct pageant_pubkey *copy = snew(struct pageant_pubkey);
  2312. copy->blob = strbuf_new();
  2313. put_data(copy->blob, orig->blob->s, orig->blob->len);
  2314. copy->comment = orig->comment ? dupstr(orig->comment) : NULL;
  2315. copy->ssh_version = orig->ssh_version;
  2316. return copy;
  2317. }
  2318. void pageant_pubkey_free(struct pageant_pubkey *key)
  2319. {
  2320. sfree(key->comment);
  2321. strbuf_free(key->blob);
  2322. sfree(key);
  2323. }