]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pageant.c
Put proper logging into Pageant.
[PuTTY.git] / pageant.c
1 /*
2  * pageant.c: cross-platform code to implement Pageant.
3  */
4
5 #include <stddef.h>
6 #include <stdlib.h>
7 #include <assert.h>
8
9 #include "putty.h"
10 #include "ssh.h"
11 #include "pageant.h"
12
13 /*
14  * We need this to link with the RSA code, because rsaencrypt()
15  * pads its data with random bytes. Since we only use rsadecrypt()
16  * and the signing functions, which are deterministic, this should
17  * never be called.
18  *
19  * If it _is_ called, there is a _serious_ problem, because it
20  * won't generate true random numbers. So we must scream, panic,
21  * and exit immediately if that should happen.
22  */
23 int random_byte(void)
24 {
25     modalfatalbox("Internal error: attempt to use random numbers in Pageant");
26     exit(0);
27     return 0;                 /* unreachable, but placate optimiser */
28 }
29
30 /*
31  * rsakeys stores SSH-1 RSA keys. ssh2keys stores all SSH-2 keys.
32  */
33 static tree234 *rsakeys, *ssh2keys;
34
35 /*
36  * Blob structure for passing to the asymmetric SSH-2 key compare
37  * function, prototyped here.
38  */
39 struct blob {
40     const unsigned char *blob;
41     int len;
42 };
43 static int cmpkeys_ssh2_asymm(void *av, void *bv);
44
45 /*
46  * Key comparison function for the 2-3-4 tree of RSA keys.
47  */
48 static int cmpkeys_rsa(void *av, void *bv)
49 {
50     struct RSAKey *a = (struct RSAKey *) av;
51     struct RSAKey *b = (struct RSAKey *) bv;
52     Bignum am, bm;
53     int alen, blen;
54
55     am = a->modulus;
56     bm = b->modulus;
57     /*
58      * Compare by length of moduli.
59      */
60     alen = bignum_bitcount(am);
61     blen = bignum_bitcount(bm);
62     if (alen > blen)
63         return +1;
64     else if (alen < blen)
65         return -1;
66     /*
67      * Now compare by moduli themselves.
68      */
69     alen = (alen + 7) / 8;             /* byte count */
70     while (alen-- > 0) {
71         int abyte, bbyte;
72         abyte = bignum_byte(am, alen);
73         bbyte = bignum_byte(bm, alen);
74         if (abyte > bbyte)
75             return +1;
76         else if (abyte < bbyte)
77             return -1;
78     }
79     /*
80      * Give up.
81      */
82     return 0;
83 }
84
85 /*
86  * Key comparison function for the 2-3-4 tree of SSH-2 keys.
87  */
88 static int cmpkeys_ssh2(void *av, void *bv)
89 {
90     struct ssh2_userkey *a = (struct ssh2_userkey *) av;
91     struct ssh2_userkey *b = (struct ssh2_userkey *) bv;
92     int i;
93     int alen, blen;
94     unsigned char *ablob, *bblob;
95     int c;
96
97     /*
98      * Compare purely by public blob.
99      */
100     ablob = a->alg->public_blob(a->data, &alen);
101     bblob = b->alg->public_blob(b->data, &blen);
102
103     c = 0;
104     for (i = 0; i < alen && i < blen; i++) {
105         if (ablob[i] < bblob[i]) {
106             c = -1;
107             break;
108         } else if (ablob[i] > bblob[i]) {
109             c = +1;
110             break;
111         }
112     }
113     if (c == 0 && i < alen)
114         c = +1;                        /* a is longer */
115     if (c == 0 && i < blen)
116         c = -1;                        /* a is longer */
117
118     sfree(ablob);
119     sfree(bblob);
120
121     return c;
122 }
123
124 /*
125  * Key comparison function for looking up a blob in the 2-3-4 tree
126  * of SSH-2 keys.
127  */
128 static int cmpkeys_ssh2_asymm(void *av, void *bv)
129 {
130     struct blob *a = (struct blob *) av;
131     struct ssh2_userkey *b = (struct ssh2_userkey *) bv;
132     int i;
133     int alen, blen;
134     const unsigned char *ablob;
135     unsigned char *bblob;
136     int c;
137
138     /*
139      * Compare purely by public blob.
140      */
141     ablob = a->blob;
142     alen = a->len;
143     bblob = b->alg->public_blob(b->data, &blen);
144
145     c = 0;
146     for (i = 0; i < alen && i < blen; i++) {
147         if (ablob[i] < bblob[i]) {
148             c = -1;
149             break;
150         } else if (ablob[i] > bblob[i]) {
151             c = +1;
152             break;
153         }
154     }
155     if (c == 0 && i < alen)
156         c = +1;                        /* a is longer */
157     if (c == 0 && i < blen)
158         c = -1;                        /* a is longer */
159
160     sfree(bblob);
161
162     return c;
163 }
164
165 /*
166  * Create an SSH-1 key list in a malloc'ed buffer; return its
167  * length.
168  */
169 void *pageant_make_keylist1(int *length)
170 {
171     int i, nkeys, len;
172     struct RSAKey *key;
173     unsigned char *blob, *p, *ret;
174     int bloblen;
175
176     /*
177      * Count up the number and length of keys we hold.
178      */
179     len = 4;
180     nkeys = 0;
181     for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
182         nkeys++;
183         blob = rsa_public_blob(key, &bloblen);
184         len += bloblen;
185         sfree(blob);
186         len += 4 + strlen(key->comment);
187     }
188
189     /* Allocate the buffer. */
190     p = ret = snewn(len, unsigned char);
191     if (length) *length = len;
192
193     PUT_32BIT(p, nkeys);
194     p += 4;
195     for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
196         blob = rsa_public_blob(key, &bloblen);
197         memcpy(p, blob, bloblen);
198         p += bloblen;
199         sfree(blob);
200         PUT_32BIT(p, strlen(key->comment));
201         memcpy(p + 4, key->comment, strlen(key->comment));
202         p += 4 + strlen(key->comment);
203     }
204
205     assert(p - ret == len);
206     return ret;
207 }
208
209 /*
210  * Create an SSH-2 key list in a malloc'ed buffer; return its
211  * length.
212  */
213 void *pageant_make_keylist2(int *length)
214 {
215     struct ssh2_userkey *key;
216     int i, len, nkeys;
217     unsigned char *blob, *p, *ret;
218     int bloblen;
219
220     /*
221      * Count up the number and length of keys we hold.
222      */
223     len = 4;
224     nkeys = 0;
225     for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
226         nkeys++;
227         len += 4;              /* length field */
228         blob = key->alg->public_blob(key->data, &bloblen);
229         len += bloblen;
230         sfree(blob);
231         len += 4 + strlen(key->comment);
232     }
233
234     /* Allocate the buffer. */
235     p = ret = snewn(len, unsigned char);
236     if (length) *length = len;
237
238     /*
239      * Packet header is the obvious five bytes, plus four
240      * bytes for the key count.
241      */
242     PUT_32BIT(p, nkeys);
243     p += 4;
244     for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
245         blob = key->alg->public_blob(key->data, &bloblen);
246         PUT_32BIT(p, bloblen);
247         p += 4;
248         memcpy(p, blob, bloblen);
249         p += bloblen;
250         sfree(blob);
251         PUT_32BIT(p, strlen(key->comment));
252         memcpy(p + 4, key->comment, strlen(key->comment));
253         p += 4 + strlen(key->comment);
254     }
255
256     assert(p - ret == len);
257     return ret;
258 }
259
260 char *fingerprint_ssh2_blob(const void *blob, int bloblen)
261 {
262     unsigned char digest[16];
263     char fingerprint_str[16*3];
264     unsigned stringlen;
265     int i;
266
267     MD5Simple(blob, bloblen, digest);
268     for (i = 0; i < 16; i++)
269         sprintf(fingerprint_str + i*3, "%02x%s", digest[i], i==15 ? "" : ":");
270
271     stringlen = GET_32BIT((const unsigned char *)blob);
272     if (stringlen < bloblen-4)
273         return dupprintf("%.*s %s", (int)stringlen, (const char *)blob + 4,
274                          fingerprint_str);
275     else
276         return dupstr(fingerprint_str);        
277 }
278
279 static void plog(void *logctx, pageant_logfn_t logfn, const char *fmt, ...)
280 #ifdef __GNUC__
281 __attribute__ ((format (printf, 3, 4)))
282 #endif
283     ;
284
285 static void plog(void *logctx, pageant_logfn_t logfn, const char *fmt, ...)
286 {
287     /*
288      * This is the wrapper that takes a variadic argument list and
289      * turns it into the va_list that the log function really expects.
290      * It's safe to call this with logfn==NULL, because we
291      * double-check that below; but if you're going to do lots of work
292      * before getting here (such as looping, or hashing things) then
293      * you should probably check logfn manually before doing that.
294      */
295     if (logfn) {
296         va_list ap;
297         va_start(ap, fmt);
298         logfn(logctx, fmt, ap);
299         va_end(ap);
300     }
301 }
302
303 void *pageant_handle_msg(const void *msg, int msglen, int *outlen,
304                          void *logctx, pageant_logfn_t logfn)
305 {
306     const unsigned char *p = msg;
307     const unsigned char *msgend;
308     unsigned char *ret = snewn(AGENT_MAX_MSGLEN, unsigned char);
309     int type;
310     const char *fail_reason;
311
312     msgend = p + msglen;
313
314     /*
315      * Get the message type.
316      */
317     if (msgend < p+1) {
318         fail_reason = "message contained no type code";
319         goto failure;
320     }
321     type = *p++;
322
323     switch (type) {
324       case SSH1_AGENTC_REQUEST_RSA_IDENTITIES:
325         /*
326          * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER.
327          */
328         {
329             int len;
330             void *keylist;
331
332             plog(logctx, logfn, "request: SSH1_AGENTC_REQUEST_RSA_IDENTITIES");
333
334             ret[4] = SSH1_AGENT_RSA_IDENTITIES_ANSWER;
335             keylist = pageant_make_keylist1(&len);
336             if (len + 5 > AGENT_MAX_MSGLEN) {
337                 sfree(keylist);
338                 fail_reason = "output would exceed max msglen";
339                 goto failure;
340             }
341             PUT_32BIT(ret, len + 1);
342             memcpy(ret + 5, keylist, len);
343
344             plog(logctx, logfn, "reply: SSH1_AGENT_RSA_IDENTITIES_ANSWER");
345             if (logfn) {               /* skip this loop if not logging */
346                 int i;
347                 struct RSAKey *rkey;
348                 for (i = 0; NULL != (rkey = pageant_nth_ssh1_key(i)); i++) {
349                     char fingerprint[128];
350                     rsa_fingerprint(fingerprint, sizeof(fingerprint), rkey);
351                     plog(logctx, logfn, "returned key: %s", fingerprint);
352                 }
353             }
354             sfree(keylist);
355         }
356         break;
357       case SSH2_AGENTC_REQUEST_IDENTITIES:
358         /*
359          * Reply with SSH2_AGENT_IDENTITIES_ANSWER.
360          */
361         {
362             int len;
363             void *keylist;
364
365             plog(logctx, logfn, "request: SSH2_AGENTC_REQUEST_IDENTITIES");
366
367             ret[4] = SSH2_AGENT_IDENTITIES_ANSWER;
368             keylist = pageant_make_keylist2(&len);
369             if (len + 5 > AGENT_MAX_MSGLEN) {
370                 sfree(keylist);
371                 fail_reason = "output would exceed max msglen";
372                 goto failure;
373             }
374             PUT_32BIT(ret, len + 1);
375             memcpy(ret + 5, keylist, len);
376
377             plog(logctx, logfn, "reply: SSH2_AGENT_IDENTITIES_ANSWER");
378             if (logfn) {               /* skip this loop if not logging */
379                 int i;
380                 struct ssh2_userkey *skey;
381                 for (i = 0; NULL != (skey = pageant_nth_ssh2_key(i)); i++) {
382                     char *fingerprint = skey->alg->fingerprint(skey->data);
383                     plog(logctx, logfn, "returned key: %s %s",
384                          fingerprint, skey->comment);
385                     sfree(fingerprint);
386                 }
387             }
388
389             sfree(keylist);
390         }
391         break;
392       case SSH1_AGENTC_RSA_CHALLENGE:
393         /*
394          * Reply with either SSH1_AGENT_RSA_RESPONSE or
395          * SSH_AGENT_FAILURE, depending on whether we have that key
396          * or not.
397          */
398         {
399             struct RSAKey reqkey, *key;
400             Bignum challenge, response;
401             unsigned char response_source[48], response_md5[16];
402             struct MD5Context md5c;
403             int i, len;
404
405             plog(logctx, logfn, "request: SSH1_AGENTC_RSA_CHALLENGE");
406
407             p += 4;
408             i = ssh1_read_bignum(p, msgend - p, &reqkey.exponent);
409             if (i < 0) {
410                 fail_reason = "request truncated before key exponent";
411                 goto failure;
412             }
413             p += i;
414             i = ssh1_read_bignum(p, msgend - p, &reqkey.modulus);
415             if (i < 0) {
416                 freebn(reqkey.exponent);
417                 fail_reason = "request truncated before key modulus";
418                 goto failure;
419             }
420             p += i;
421             i = ssh1_read_bignum(p, msgend - p, &challenge);
422             if (i < 0) {
423                 freebn(reqkey.exponent);
424                 freebn(reqkey.modulus);
425                 fail_reason = "request truncated before challenge";
426                 goto failure;
427             }
428             p += i;
429             if (msgend < p+16) {
430                 freebn(reqkey.exponent);
431                 freebn(reqkey.modulus);
432                 freebn(challenge);
433                 fail_reason = "request truncated before session id";
434                 goto failure;
435             }
436             memcpy(response_source + 32, p, 16);
437             p += 16;
438             if (msgend < p+4) {
439                 freebn(reqkey.exponent);
440                 freebn(reqkey.modulus);
441                 freebn(challenge);
442                 fail_reason = "request truncated before response type";
443                 goto failure;
444             }
445             if (GET_32BIT(p) != 1) {
446                 freebn(reqkey.exponent);
447                 freebn(reqkey.modulus);
448                 freebn(challenge);
449                 fail_reason = "response type other than 1 not supported";
450                 goto failure;
451             }
452             if (logfn) {
453                 char fingerprint[128];
454                 reqkey.comment = NULL;
455                 rsa_fingerprint(fingerprint, sizeof(fingerprint), &reqkey);
456                 plog(logctx, logfn, "requested key: %s", fingerprint);
457             }
458             if ((key = find234(rsakeys, &reqkey, NULL)) == NULL) {
459                 freebn(reqkey.exponent);
460                 freebn(reqkey.modulus);
461                 freebn(challenge);
462                 fail_reason = "key not found";
463                 goto failure;
464             }
465             response = rsadecrypt(challenge, key);
466             for (i = 0; i < 32; i++)
467                 response_source[i] = bignum_byte(response, 31 - i);
468
469             MD5Init(&md5c);
470             MD5Update(&md5c, response_source, 48);
471             MD5Final(response_md5, &md5c);
472             smemclr(response_source, 48);       /* burn the evidence */
473             freebn(response);          /* and that evidence */
474             freebn(challenge);         /* yes, and that evidence */
475             freebn(reqkey.exponent);   /* and free some memory ... */
476             freebn(reqkey.modulus);    /* ... while we're at it. */
477
478             /*
479              * Packet is the obvious five byte header, plus sixteen
480              * bytes of MD5.
481              */
482             len = 5 + 16;
483             PUT_32BIT(ret, len - 4);
484             ret[4] = SSH1_AGENT_RSA_RESPONSE;
485             memcpy(ret + 5, response_md5, 16);
486
487             plog(logctx, logfn, "reply: SSH1_AGENT_RSA_RESPONSE");
488         }
489         break;
490       case SSH2_AGENTC_SIGN_REQUEST:
491         /*
492          * Reply with either SSH2_AGENT_SIGN_RESPONSE or
493          * SSH_AGENT_FAILURE, depending on whether we have that key
494          * or not.
495          */
496         {
497             struct ssh2_userkey *key;
498             struct blob b;
499             const unsigned char *data;
500             unsigned char *signature;
501             int datalen, siglen, len;
502
503             plog(logctx, logfn, "request: SSH2_AGENTC_SIGN_REQUEST");
504
505             if (msgend < p+4) {
506                 fail_reason = "request truncated before public key";
507                 goto failure;
508             }
509             b.len = toint(GET_32BIT(p));
510             if (b.len < 0 || b.len > msgend - (p+4)) {
511                 fail_reason = "request truncated before public key";
512                 goto failure;
513             }
514             p += 4;
515             b.blob = p;
516             p += b.len;
517             if (msgend < p+4) {
518                 fail_reason = "request truncated before string to sign";
519                 goto failure;
520             }
521             datalen = toint(GET_32BIT(p));
522             p += 4;
523             if (datalen < 0 || datalen > msgend - p) {
524                 fail_reason = "request truncated before string to sign";
525                 goto failure;
526             }
527             data = p;
528             if (logfn) {
529                 char *fingerprint = fingerprint_ssh2_blob(b.blob, b.len);
530                 plog(logctx, logfn, "requested key: %s", fingerprint);
531                 sfree(fingerprint);
532             }
533             key = find234(ssh2keys, &b, cmpkeys_ssh2_asymm);
534             if (!key) {
535                 fail_reason = "key not found";
536                 goto failure;
537             }
538             signature = key->alg->sign(key->data, (const char *)data,
539                                        datalen, &siglen);
540             len = 5 + 4 + siglen;
541             PUT_32BIT(ret, len - 4);
542             ret[4] = SSH2_AGENT_SIGN_RESPONSE;
543             PUT_32BIT(ret + 5, siglen);
544             memcpy(ret + 5 + 4, signature, siglen);
545             sfree(signature);
546
547             plog(logctx, logfn, "reply: SSH2_AGENT_SIGN_RESPONSE");
548         }
549         break;
550       case SSH1_AGENTC_ADD_RSA_IDENTITY:
551         /*
552          * Add to the list and return SSH_AGENT_SUCCESS, or
553          * SSH_AGENT_FAILURE if the key was malformed.
554          */
555         {
556             struct RSAKey *key;
557             char *comment;
558             int n, commentlen;
559
560             plog(logctx, logfn, "request: SSH1_AGENTC_ADD_RSA_IDENTITY");
561
562             key = snew(struct RSAKey);
563             memset(key, 0, sizeof(struct RSAKey));
564
565             n = makekey(p, msgend - p, key, NULL, 1);
566             if (n < 0) {
567                 freersakey(key);
568                 sfree(key);
569                 fail_reason = "request truncated before public key";
570                 goto failure;
571             }
572             p += n;
573
574             n = makeprivate(p, msgend - p, key);
575             if (n < 0) {
576                 freersakey(key);
577                 sfree(key);
578                 fail_reason = "request truncated before private key";
579                 goto failure;
580             }
581             p += n;
582
583             n = ssh1_read_bignum(p, msgend - p, &key->iqmp);  /* p^-1 mod q */
584             if (n < 0) {
585                 freersakey(key);
586                 sfree(key);
587                 fail_reason = "request truncated before iqmp";
588                 goto failure;
589             }
590             p += n;
591
592             n = ssh1_read_bignum(p, msgend - p, &key->p);  /* p */
593             if (n < 0) {
594                 freersakey(key);
595                 sfree(key);
596                 fail_reason = "request truncated before p";
597                 goto failure;
598             }
599             p += n;
600
601             n = ssh1_read_bignum(p, msgend - p, &key->q);  /* q */
602             if (n < 0) {
603                 freersakey(key);
604                 sfree(key);
605                 fail_reason = "request truncated before q";
606                 goto failure;
607             }
608             p += n;
609
610             if (msgend < p+4) {
611                 freersakey(key);
612                 sfree(key);
613                 fail_reason = "request truncated before key comment";
614                 goto failure;
615             }
616             commentlen = toint(GET_32BIT(p));
617
618             if (commentlen < 0 || commentlen > msgend - p) {
619                 freersakey(key);
620                 sfree(key);
621                 fail_reason = "request truncated before key comment";
622                 goto failure;
623             }
624
625             comment = snewn(commentlen+1, char);
626             if (comment) {
627                 memcpy(comment, p + 4, commentlen);
628                 comment[commentlen] = '\0';
629                 key->comment = comment;
630             }
631
632             if (logfn) {
633                 char fingerprint[128];
634                 rsa_fingerprint(fingerprint, sizeof(fingerprint), key);
635                 plog(logctx, logfn, "submitted key: %s", fingerprint);
636             }
637
638             if (add234(rsakeys, key) == key) {
639                 keylist_update();
640                 PUT_32BIT(ret, 1);
641                 ret[4] = SSH_AGENT_SUCCESS;
642
643                 plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
644             } else {
645                 freersakey(key);
646                 sfree(key);
647
648                 fail_reason = "key already present";
649                 goto failure;
650             }
651         }
652         break;
653       case SSH2_AGENTC_ADD_IDENTITY:
654         /*
655          * Add to the list and return SSH_AGENT_SUCCESS, or
656          * SSH_AGENT_FAILURE if the key was malformed.
657          */
658         {
659             struct ssh2_userkey *key;
660             char *comment;
661             const char *alg;
662             int alglen, commlen;
663             int bloblen;
664
665             plog(logctx, logfn, "request: SSH2_AGENTC_ADD_IDENTITY");
666
667             if (msgend < p+4) {
668                 fail_reason = "request truncated before key algorithm";
669                 goto failure;
670             }
671             alglen = toint(GET_32BIT(p));
672             p += 4;
673             if (alglen < 0 || alglen > msgend - p) {
674                 fail_reason = "request truncated before key algorithm";
675                 goto failure;
676             }
677             alg = (const char *)p;
678             p += alglen;
679
680             key = snew(struct ssh2_userkey);
681             /* Add further algorithm names here. */
682             if (alglen == 7 && !memcmp(alg, "ssh-rsa", 7))
683                 key->alg = &ssh_rsa;
684             else if (alglen == 7 && !memcmp(alg, "ssh-dss", 7))
685                 key->alg = &ssh_dss;
686             else if (alglen == 19 && memcmp(alg, "ecdsa-sha2-nistp256", 19))
687                 key->alg = &ssh_ecdsa_nistp256;
688             else if (alglen == 19 && memcmp(alg, "ecdsa-sha2-nistp384", 19))
689                 key->alg = &ssh_ecdsa_nistp384;
690             else if (alglen == 19 && memcmp(alg, "ecdsa-sha2-nistp521", 19))
691                 key->alg = &ssh_ecdsa_nistp521;
692             else {
693                 sfree(key);
694                 fail_reason = "algorithm unknown";
695                 goto failure;
696             }
697
698             bloblen = msgend - p;
699             key->data = key->alg->openssh_createkey(&p, &bloblen);
700             if (!key->data) {
701                 sfree(key);
702                 fail_reason = "key setup failed";
703                 goto failure;
704             }
705
706             /*
707              * p has been advanced by openssh_createkey, but
708              * certainly not _beyond_ the end of the buffer.
709              */
710             assert(p <= msgend);
711
712             if (msgend < p+4) {
713                 key->alg->freekey(key->data);
714                 sfree(key);
715                 fail_reason = "request truncated before key comment";
716                 goto failure;
717             }
718             commlen = toint(GET_32BIT(p));
719             p += 4;
720
721             if (commlen < 0 || commlen > msgend - p) {
722                 key->alg->freekey(key->data);
723                 sfree(key);
724                 fail_reason = "request truncated before key comment";
725                 goto failure;
726             }
727             comment = snewn(commlen + 1, char);
728             if (comment) {
729                 memcpy(comment, p, commlen);
730                 comment[commlen] = '\0';
731             }
732             key->comment = comment;
733
734             if (logfn) {
735                 char *fingerprint = key->alg->fingerprint(key->data);
736                 plog(logctx, logfn, "submitted key: %s %s",
737                      fingerprint, key->comment);
738                 sfree(fingerprint);
739             }
740
741             if (add234(ssh2keys, key) == key) {
742                 keylist_update();
743                 PUT_32BIT(ret, 1);
744                 ret[4] = SSH_AGENT_SUCCESS;
745
746                 plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
747             } else {
748                 key->alg->freekey(key->data);
749                 sfree(key->comment);
750                 sfree(key);
751
752                 fail_reason = "key already present";
753                 goto failure;
754             }
755         }
756         break;
757       case SSH1_AGENTC_REMOVE_RSA_IDENTITY:
758         /*
759          * Remove from the list and return SSH_AGENT_SUCCESS, or
760          * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
761          * start with.
762          */
763         {
764             struct RSAKey reqkey, *key;
765             int n;
766
767             plog(logctx, logfn, "request: SSH1_AGENTC_REMOVE_RSA_IDENTITY");
768
769             n = makekey(p, msgend - p, &reqkey, NULL, 0);
770             if (n < 0) {
771                 fail_reason = "request truncated before public key";
772                 goto failure;
773             }
774
775             if (logfn) {
776                 char fingerprint[128];
777                 reqkey.comment = NULL;
778                 rsa_fingerprint(fingerprint, sizeof(fingerprint), &reqkey);
779                 plog(logctx, logfn, "unwanted key: %s", fingerprint);
780             }
781
782             key = find234(rsakeys, &reqkey, NULL);
783             freebn(reqkey.exponent);
784             freebn(reqkey.modulus);
785             PUT_32BIT(ret, 1);
786             if (key) {
787                 plog(logctx, logfn, "found with comment: %s", key->comment);
788
789                 del234(rsakeys, key);
790                 keylist_update();
791                 freersakey(key);
792                 sfree(key);
793                 ret[4] = SSH_AGENT_SUCCESS;
794
795                 plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
796             } else {
797                 fail_reason = "key not found";
798                 goto failure;
799             }
800         }
801         break;
802       case SSH2_AGENTC_REMOVE_IDENTITY:
803         /*
804          * Remove from the list and return SSH_AGENT_SUCCESS, or
805          * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
806          * start with.
807          */
808         {
809             struct ssh2_userkey *key;
810             struct blob b;
811
812             plog(logctx, logfn, "request: SSH2_AGENTC_REMOVE_IDENTITY");
813
814             if (msgend < p+4) {
815                 fail_reason = "request truncated before public key";
816                 goto failure;
817             }
818             b.len = toint(GET_32BIT(p));
819             p += 4;
820
821             if (b.len < 0 || b.len > msgend - p) {
822                 fail_reason = "request truncated before public key";
823                 goto failure;
824             }
825             b.blob = p;
826             p += b.len;
827
828             if (logfn) {
829                 char *fingerprint = fingerprint_ssh2_blob(b.blob, b.len);
830                 plog(logctx, logfn, "unwanted key: %s", fingerprint);
831                 sfree(fingerprint);
832             }
833
834             key = find234(ssh2keys, &b, cmpkeys_ssh2_asymm);
835             if (!key) {
836                 fail_reason = "key not found";
837                 goto failure;
838             }
839
840             plog(logctx, logfn, "found with comment: %s", key->comment);
841
842             del234(ssh2keys, key);
843             keylist_update();
844             key->alg->freekey(key->data);
845             sfree(key);
846             PUT_32BIT(ret, 1);
847             ret[4] = SSH_AGENT_SUCCESS;
848
849             plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
850         }
851         break;
852       case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
853         /*
854          * Remove all SSH-1 keys. Always returns success.
855          */
856         {
857             struct RSAKey *rkey;
858
859             plog(logctx, logfn, "request:"
860                 " SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES");
861
862             while ((rkey = index234(rsakeys, 0)) != NULL) {
863                 del234(rsakeys, rkey);
864                 freersakey(rkey);
865                 sfree(rkey);
866             }
867             keylist_update();
868
869             PUT_32BIT(ret, 1);
870             ret[4] = SSH_AGENT_SUCCESS;
871
872             plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
873         }
874         break;
875       case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
876         /*
877          * Remove all SSH-2 keys. Always returns success.
878          */
879         {
880             struct ssh2_userkey *skey;
881
882             plog(logctx, logfn, "request: SSH2_AGENTC_REMOVE_ALL_IDENTITIES");
883
884             while ((skey = index234(ssh2keys, 0)) != NULL) {
885                 del234(ssh2keys, skey);
886                 skey->alg->freekey(skey->data);
887                 sfree(skey);
888             }
889             keylist_update();
890
891             PUT_32BIT(ret, 1);
892             ret[4] = SSH_AGENT_SUCCESS;
893
894             plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS");
895         }
896         break;
897       default:
898         plog(logctx, logfn, "request: unknown message type %d", type);
899
900         fail_reason = "unrecognised message";
901         /* fall through */
902       failure:
903         /*
904          * Unrecognised message. Return SSH_AGENT_FAILURE.
905          */
906         PUT_32BIT(ret, 1);
907         ret[4] = SSH_AGENT_FAILURE;
908         plog(logctx, logfn, "reply: SSH_AGENT_FAILURE (%s)", fail_reason);
909         break;
910     }
911
912     *outlen = 4 + GET_32BIT(ret);
913     return ret;
914 }
915
916 void *pageant_failure_msg(int *outlen)
917 {
918     unsigned char *ret = snewn(5, unsigned char);
919     PUT_32BIT(ret, 1);
920     ret[4] = SSH_AGENT_FAILURE;
921     *outlen = 5;
922     return ret;
923 }
924
925 void pageant_init(void)
926 {
927     rsakeys = newtree234(cmpkeys_rsa);
928     ssh2keys = newtree234(cmpkeys_ssh2);
929 }
930
931 struct RSAKey *pageant_nth_ssh1_key(int i)
932 {
933     return index234(rsakeys, i);
934 }
935
936 struct ssh2_userkey *pageant_nth_ssh2_key(int i)
937 {
938     return index234(ssh2keys, i);
939 }
940
941 int pageant_count_ssh1_keys(void)
942 {
943     return count234(rsakeys);
944 }
945
946 int pageant_count_ssh2_keys(void)
947 {
948     return count234(ssh2keys);
949 }
950
951 int pageant_add_ssh1_key(struct RSAKey *rkey)
952 {
953     return add234(rsakeys, rkey) != rkey;
954 }
955
956 int pageant_add_ssh2_key(struct ssh2_userkey *skey)
957 {
958     return add234(ssh2keys, skey) != skey;
959 }
960
961 int pageant_delete_ssh1_key(struct RSAKey *rkey)
962 {
963     struct RSAKey *deleted = del234(rsakeys, rkey);
964     if (!deleted)
965         return FALSE;
966     assert(deleted == rkey);
967     return TRUE;
968 }
969
970 int pageant_delete_ssh2_key(struct ssh2_userkey *skey)
971 {
972     struct ssh2_userkey *deleted = del234(ssh2keys, skey);
973     if (!deleted)
974         return FALSE;
975     assert(deleted == skey);
976     return TRUE;
977 }
978
979 /* ----------------------------------------------------------------------
980  * The agent plug.
981  */
982
983 /*
984  * Coroutine macros similar to, but simplified from, those in ssh.c.
985  */
986 #define crBegin(v)      { int *crLine = &v; switch(v) { case 0:;
987 #define crFinish(z)     } *crLine = 0; return (z); }
988 #define crGetChar(c) do                                         \
989     {                                                           \
990         while (len == 0) {                                      \
991             *crLine =__LINE__; return 1; case __LINE__:;        \
992         }                                                       \
993         len--;                                                  \
994         (c) = (unsigned char)*data++;                           \
995     } while (0)
996
997 struct pageant_conn_state {
998     const struct plug_function_table *fn;
999     /* the above variable absolutely *must* be the first in this structure */
1000
1001     Socket connsock;
1002     void *logctx;
1003     pageant_logfn_t logfn;
1004     unsigned char lenbuf[4], pktbuf[AGENT_MAX_MSGLEN];
1005     unsigned len, got;
1006     int real_packet;
1007     int crLine;            /* for coroutine in pageant_conn_receive */
1008 };
1009
1010 static int pageant_conn_closing(Plug plug, const char *error_msg,
1011                                 int error_code, int calling_back)
1012 {
1013     struct pageant_conn_state *pc = (struct pageant_conn_state *)plug;
1014     if (error_msg)
1015         plog(pc->logctx, pc->logfn, "%p: error: %s", pc, error_msg);
1016     else
1017         plog(pc->logctx, pc->logfn, "%p: connection closed", pc);
1018     sk_close(pc->connsock);
1019     sfree(pc);
1020     return 1;
1021 }
1022
1023 static void pageant_conn_sent(Plug plug, int bufsize)
1024 {
1025     /* struct pageant_conn_state *pc = (struct pageant_conn_state *)plug; */
1026
1027     /*
1028      * We do nothing here, because we expect that there won't be a
1029      * need to throttle and unthrottle the connection to an agent -
1030      * clients will typically not send many requests, and will wait
1031      * until they receive each reply before sending a new request.
1032      */
1033 }
1034
1035 static void pageant_conn_log(void *logctx, const char *fmt, va_list ap)
1036 {
1037     /* Wrapper on pc->logfn that prefixes the connection identifier */
1038     struct pageant_conn_state *pc = (struct pageant_conn_state *)logctx;
1039     char *formatted = dupvprintf(fmt, ap);
1040     plog(pc->logctx, pc->logfn, "%p: %s", pc, formatted);
1041     sfree(formatted);
1042 }
1043
1044 static int pageant_conn_receive(Plug plug, int urgent, char *data, int len)
1045 {
1046     struct pageant_conn_state *pc = (struct pageant_conn_state *)plug;
1047     char c;
1048
1049     crBegin(pc->crLine);
1050
1051     while (len > 0) {
1052         pc->got = 0;
1053         while (pc->got < 4) {
1054             crGetChar(c);
1055             pc->lenbuf[pc->got++] = c;
1056         }
1057
1058         pc->len = GET_32BIT(pc->lenbuf);
1059         pc->got = 0;
1060         pc->real_packet = (pc->len < AGENT_MAX_MSGLEN-4);
1061
1062         while (pc->got < pc->len) {
1063             crGetChar(c);
1064             if (pc->real_packet)
1065                 pc->pktbuf[pc->got] = c;
1066             pc->got++;
1067         }
1068
1069         {
1070             void *reply;
1071             int replylen;
1072
1073             if (pc->real_packet) {
1074                 reply = pageant_handle_msg(pc->pktbuf, pc->len, &replylen, pc,
1075                                            pc->logfn?pageant_conn_log:NULL);
1076             } else {
1077                 plog(pc->logctx, pc->logfn, "%p: overlong message (%u)",
1078                      pc, pc->len);
1079                 plog(pc->logctx, pc->logfn, "%p: reply: SSH_AGENT_FAILURE "
1080                      "(message too long)", pc);
1081                 reply = pageant_failure_msg(&replylen);
1082             }
1083             sk_write(pc->connsock, reply, replylen);
1084             smemclr(reply, replylen);
1085         }
1086     }
1087
1088     crFinish(1);
1089 }
1090
1091 struct pageant_listen_state {
1092     const struct plug_function_table *fn;
1093     /* the above variable absolutely *must* be the first in this structure */
1094
1095     Socket listensock;
1096     void *logctx;
1097     pageant_logfn_t logfn;
1098 };
1099
1100 static int pageant_listen_closing(Plug plug, const char *error_msg,
1101                                   int error_code, int calling_back)
1102 {
1103     struct pageant_listen_state *pl = (struct pageant_listen_state *)plug;
1104     if (error_msg)
1105         plog(pl->logctx, pl->logfn, "listening socket: error: %s", error_msg);
1106     sk_close(pl->listensock);
1107     pl->listensock = NULL;
1108     return 1;
1109 }
1110
1111 static int pageant_listen_accepting(Plug plug,
1112                                     accept_fn_t constructor, accept_ctx_t ctx)
1113 {
1114     static const struct plug_function_table connection_fn_table = {
1115         NULL, /* no log function, because that's for outgoing connections */
1116         pageant_conn_closing,
1117         pageant_conn_receive,
1118         pageant_conn_sent,
1119         NULL /* no accepting function, because we've already done it */
1120     };
1121     struct pageant_listen_state *pl = (struct pageant_listen_state *)plug;
1122     struct pageant_conn_state *pc;
1123     const char *err;
1124
1125     pc = snew(struct pageant_conn_state);
1126     pc->fn = &connection_fn_table;
1127     pc->logfn = pl->logfn;
1128     pc->logctx = pl->logctx;
1129     pc->crLine = 0;
1130
1131     pc->connsock = constructor(ctx, (Plug) pc);
1132     if ((err = sk_socket_error(pc->connsock)) != NULL) {
1133         sk_close(pc->connsock);
1134         sfree(pc);
1135         return TRUE;
1136     }
1137
1138     sk_set_frozen(pc->connsock, 0);
1139
1140     /* FIXME: can we get any useful peer id info? */
1141     plog(pl->logctx, pl->logfn, "%p: new connection", pc);
1142
1143     return 0;
1144 }
1145
1146 struct pageant_listen_state *pageant_listener_new(void *logctx,
1147                                                   pageant_logfn_t logfn)
1148 {
1149     static const struct plug_function_table listener_fn_table = {
1150         NULL, /* no log function, because that's for outgoing connections */
1151         pageant_listen_closing,
1152         NULL, /* no receive function on a listening socket */
1153         NULL, /* no sent function on a listening socket */
1154         pageant_listen_accepting
1155     };
1156
1157     struct pageant_listen_state *pl = snew(struct pageant_listen_state);
1158     pl->fn = &listener_fn_table;
1159     pl->logctx = logctx;
1160     pl->logfn = logfn;
1161     pl->listensock = NULL;
1162     return pl;
1163 }
1164
1165 void pageant_listener_got_socket(struct pageant_listen_state *pl, Socket sock)
1166 {
1167     pl->listensock = sock;
1168 }
1169
1170 void pageant_listener_free(struct pageant_listen_state *pl)
1171 {
1172     if (pl->listensock)
1173         sk_close(pl->listensock);
1174     sfree(pl);
1175 }