]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
SSH2 is now more plausible - window sizes listened to, basic non-crashing
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <winsock.h>
6
7 #include "putty.h"
8 #include "tree234.h"
9 #include "ssh.h"
10 #include "scp.h"
11
12 #ifndef FALSE
13 #define FALSE 0
14 #endif
15 #ifndef TRUE
16 #define TRUE 1
17 #endif
18
19 #define logevent(s) { logevent(s); \
20                       if (!(flags & FLAG_CONNECTION) && (flags & FLAG_VERBOSE)) \
21                       fprintf(stderr, "%s\n", s); }
22
23 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
24 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
25 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
26 #define SSH1_CMSG_USER                            4    /* 0x4 */
27 #define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
30 #define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
31 #define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
32 #define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
33 #define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
34 #define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
35 #define SSH1_SMSG_SUCCESS                         14   /* 0xe */
36 #define SSH1_SMSG_FAILURE                         15   /* 0xf */
37 #define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
38 #define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
39 #define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
40 #define SSH1_CMSG_EOF                             19   /* 0x13 */
41 #define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
44 #define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
45 #define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
47 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
48 #define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
49 #define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
50 #define SSH1_MSG_IGNORE                           32   /* 0x20 */
51 #define SSH1_MSG_DEBUG                            36   /* 0x24 */
52 #define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
58
59 #define SSH1_AUTH_TIS                             5    /* 0x5 */
60 #define SSH1_AUTH_CCARD                           16   /* 0x10 */
61
62 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES         1    /* 0x1 */
63 #define SSH_AGENT_RSA_IDENTITIES_ANSWER           2    /* 0x2 */
64 #define SSH_AGENTC_RSA_CHALLENGE                  3    /* 0x3 */
65 #define SSH_AGENT_RSA_RESPONSE                    4    /* 0x4 */
66 #define SSH_AGENT_FAILURE                         5    /* 0x5 */
67 #define SSH_AGENT_SUCCESS                         6    /* 0x6 */
68 #define SSH_AGENTC_ADD_RSA_IDENTITY               7    /* 0x7 */
69 #define SSH_AGENTC_REMOVE_RSA_IDENTITY            8    /* 0x8 */
70
71 #define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
72 #define SSH2_MSG_IGNORE                           2    /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
74 #define SSH2_MSG_DEBUG                            4    /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
77 #define SSH2_MSG_KEXINIT                          20   /* 0x14 */
78 #define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
81 #define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
82 #define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
83 #define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
84 #define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
85 #define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
86 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
87 #define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
88 #define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
89 #define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
90 #define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
91 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
92 #define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
93 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
94 #define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
95 #define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
96 #define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
97 #define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
98 #define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
99 #define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
100 #define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
101
102 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
103 #define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
104 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
105 #define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
106
107 #define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
108
109 #define GET_32BIT(cp) \
110     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
111     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
112     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
113     ((unsigned long)(unsigned char)(cp)[3]))
114
115 #define PUT_32BIT(cp, value) { \
116     (cp)[0] = (unsigned char)((value) >> 24); \
117     (cp)[1] = (unsigned char)((value) >> 16); \
118     (cp)[2] = (unsigned char)((value) >> 8); \
119     (cp)[3] = (unsigned char)(value); }
120
121 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
122
123 /* Coroutine mechanics for the sillier bits of the code */
124 #define crBegin1        static int crLine = 0;
125 #define crBegin2        switch(crLine) { case 0:;
126 #define crBegin         crBegin1; crBegin2;
127 #define crFinish(z)     } crLine = 0; return (z)
128 #define crFinishV       } crLine = 0; return
129 #define crReturn(z)     \
130         do {\
131             crLine=__LINE__; return (z); case __LINE__:;\
132         } while (0)
133 #define crReturnV       \
134         do {\
135             crLine=__LINE__; return; case __LINE__:;\
136         } while (0)
137 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
138 #define crStopV         do{ crLine = 0; return; }while(0)
139 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
140 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
141
142 extern struct ssh_cipher ssh_3des;
143 extern struct ssh_cipher ssh_3des_ssh2;
144 extern struct ssh_cipher ssh_des;
145 extern struct ssh_cipher ssh_blowfish;
146
147 /* for ssh 2; we miss out single-DES because it isn't supported */
148 struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
149
150 extern struct ssh_kex ssh_diffiehellman;
151 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
152
153 extern struct ssh_hostkey ssh_dss;
154 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
155
156 extern struct ssh_mac ssh_sha1;
157
158 static SHA_State exhash;
159
160 static void nullmac_key(unsigned char *key) { }
161 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
162 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
163 struct ssh_mac ssh_mac_none = {
164     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
165 };
166 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
167
168 struct ssh_compress ssh_comp_none = {
169     "none"
170 };
171 struct ssh_compress *compressions[] = { &ssh_comp_none };
172
173 static SOCKET s = INVALID_SOCKET;
174
175 static unsigned char session_key[32];
176 static struct ssh_cipher *cipher = NULL;
177 static struct ssh_cipher *cscipher = NULL;
178 static struct ssh_cipher *sccipher = NULL;
179 static struct ssh_mac *csmac = NULL;
180 static struct ssh_mac *scmac = NULL;
181 static struct ssh_compress *cscomp = NULL;
182 static struct ssh_compress *sccomp = NULL;
183 static struct ssh_kex *kex = NULL;
184 static struct ssh_hostkey *hostkey = NULL;
185 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
186
187 static char *savedhost;
188 static int ssh_send_ok;
189
190 /*
191  * 2-3-4 tree storing channels.
192  */
193 struct ssh_channel {
194     unsigned remoteid, localid;
195     int type;
196     int closes;
197     union {
198         struct ssh_agent_channel {
199             unsigned char *message;
200             unsigned char msglen[4];
201             int lensofar, totallen;
202         } a;
203         struct ssh2_data_channel {
204             unsigned char *outbuffer;
205             unsigned outbuflen, outbufsize;
206             unsigned remwindow, remmaxpkt;
207         } v2;
208     } u;
209 };
210 static tree234 *ssh_channels;           /* indexed by local id */
211 static int ssh_channelcmp(void *av, void *bv) {
212     struct ssh_channel *a = (struct ssh_channel *)av;
213     struct ssh_channel *b = (struct ssh_channel *)bv;
214     if (a->localid < b->localid) return -1;
215     if (a->localid > b->localid) return +1;
216     return 0;
217 }
218 static int ssh_channelfind(void *av, void *bv) {
219     unsigned *a = (unsigned *)av;
220     struct ssh_channel *b = (struct ssh_channel *)bv;
221     if (*a < b->localid) return -1;
222     if (*a > b->localid) return +1;
223     return 0;
224 }
225
226 static struct ssh_channel *mainchan;   /* primary session channel */
227
228 static enum {
229     SSH_STATE_BEFORE_SIZE,
230     SSH_STATE_INTERMED,
231     SSH_STATE_SESSION,
232     SSH_STATE_CLOSED
233 } ssh_state = SSH_STATE_BEFORE_SIZE;
234
235 static int size_needed = FALSE;
236
237 static void s_write (char *buf, int len) {
238     while (len > 0) {
239         int i = send (s, buf, len, 0);
240         noise_ultralight(i);
241         if (i <= 0)
242             fatalbox("Lost connection while sending");
243         if (i > 0)
244             len -= i, buf += i;
245     }
246 }
247
248 static int s_read (char *buf, int len) {
249     int ret = 0;
250     while (len > 0) {
251         int i = recv (s, buf, len, 0);
252         noise_ultralight(i);
253         if (i > 0)
254             len -= i, buf += i, ret += i;
255         else
256             return i;
257     }
258     return ret;
259 }
260
261 static void c_write (char *buf, int len) {
262     if (!(flags & FLAG_CONNECTION)) {
263         int i;
264         for (i = 0; i < len; i++)
265             if (buf[i] != '\r')
266                 fputc(buf[i], stderr);
267         return;
268     }
269     while (len--) 
270         c_write1(*buf++);
271 }
272
273 struct Packet {
274     long length;
275     int type;
276     unsigned char *data;
277     unsigned char *body;
278     long savedpos;
279     long maxlen;
280 };
281
282 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
283 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
284
285 static int ssh_version;
286 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
287 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
288 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
289 static void ssh_size(void);
290
291 static int (*s_rdpkt)(unsigned char **data, int *datalen);
292
293 /*
294  * Collect incoming data in the incoming packet buffer.
295  * Decipher and verify the packet when it is completely read.
296  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
297  * Update the *data and *datalen variables.
298  * Return the additional nr of bytes needed, or 0 when
299  * a complete packet is available.
300  */
301 static int ssh1_rdpkt(unsigned char **data, int *datalen)
302 {
303     static long len, pad, biglen, to_read;
304     static unsigned long realcrc, gotcrc;
305     static unsigned char *p;
306     static int i;
307
308     crBegin;
309
310 next_packet:
311
312     pktin.type = 0;
313     pktin.length = 0;
314
315     for (i = len = 0; i < 4; i++) {
316         while ((*datalen) == 0)
317             crReturn(4-i);
318         len = (len << 8) + **data;
319         (*data)++, (*datalen)--;
320     }
321
322 #ifdef FWHACK
323     if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
324         len = 0x300;               /* big enough to carry to end */
325     }
326 #endif
327
328     pad = 8 - (len % 8);
329     biglen = len + pad;
330     pktin.length = len - 5;
331
332     if (pktin.maxlen < biglen) {
333         pktin.maxlen = biglen;
334         pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
335                       realloc(pktin.data, biglen+APIEXTRA));
336         if (!pktin.data)
337             fatalbox("Out of memory");
338     }
339
340     to_read = biglen;
341     p = pktin.data;
342     while (to_read > 0) {
343         static int chunk;
344         chunk = to_read;
345         while ((*datalen) == 0)
346             crReturn(to_read);
347         if (chunk > (*datalen))
348             chunk = (*datalen);
349         memcpy(p, *data, chunk);
350         *data += chunk;
351         *datalen -= chunk;
352         p += chunk;
353         to_read -= chunk;
354     }
355
356     if (cipher)
357         cipher->decrypt(pktin.data, biglen);
358
359     pktin.type = pktin.data[pad];
360     pktin.body = pktin.data + pad + 1;
361
362     realcrc = crc32(pktin.data, biglen-4);
363     gotcrc = GET_32BIT(pktin.data+biglen-4);
364     if (gotcrc != realcrc) {
365         fatalbox("Incorrect CRC received on packet");
366     }
367
368     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
369         pktin.type == SSH1_SMSG_STDERR_DATA ||
370         pktin.type == SSH1_MSG_DEBUG ||
371         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
372         pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
373         long strlen = GET_32BIT(pktin.body);
374         if (strlen + 4 != pktin.length)
375             fatalbox("Received data packet with bogus string length");
376     }
377
378     if (pktin.type == SSH1_MSG_DEBUG) {
379         /* log debug message */
380         char buf[80];
381         int strlen = GET_32BIT(pktin.body);
382         strcpy(buf, "Remote: ");
383         if (strlen > 70) strlen = 70;
384         memcpy(buf+8, pktin.body+4, strlen);
385         buf[8+strlen] = '\0';
386         logevent(buf);
387         goto next_packet;
388     } else if (pktin.type == SSH1_MSG_IGNORE) {
389         /* do nothing */
390         goto next_packet;
391     }
392
393     crFinish(0);
394 }
395
396 static int ssh2_rdpkt(unsigned char **data, int *datalen)
397 {
398     static long len, pad, payload, packetlen, maclen;
399     static int i;
400     static int cipherblk;
401     static unsigned long incoming_sequence = 0;
402
403     crBegin;
404
405 next_packet:
406
407     pktin.type = 0;
408     pktin.length = 0;
409
410     if (cipher)
411         cipherblk = cipher->blksize;
412     else
413         cipherblk = 8;
414     if (cipherblk < 8)
415         cipherblk = 8;
416
417     if (pktin.maxlen < cipherblk) {
418         pktin.maxlen = cipherblk;
419         pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
420                       realloc(pktin.data, cipherblk+APIEXTRA));
421         if (!pktin.data)
422             fatalbox("Out of memory");
423     }
424
425     /*
426      * Acquire and decrypt the first block of the packet. This will
427      * contain the length and padding details.
428      */
429      for (i = len = 0; i < cipherblk; i++) {
430         while ((*datalen) == 0)
431             crReturn(cipherblk-i);
432         pktin.data[i] = *(*data)++;
433         (*datalen)--;
434     }
435 #ifdef FWHACK
436     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
437         /* FIXME */
438     }
439 #endif
440     if (sccipher)
441         sccipher->decrypt(pktin.data, cipherblk);
442
443     /*
444      * Now get the length and padding figures.
445      */
446     len = GET_32BIT(pktin.data);
447     pad = pktin.data[4];
448
449     /*
450      * This enables us to deduce the payload length.
451      */
452     payload = len - pad - 1;
453
454     pktin.length = payload + 5;
455
456     /*
457      * So now we can work out the total packet length.
458      */
459     packetlen = len + 4;
460     maclen = scmac ? scmac->len : 0;
461
462     /*
463      * Adjust memory allocation if packet is too big.
464      */
465     if (pktin.maxlen < packetlen+maclen) {
466         pktin.maxlen = packetlen+maclen;
467         pktin.data = (pktin.data == NULL ? malloc(pktin.maxlen+APIEXTRA) :
468                       realloc(pktin.data, pktin.maxlen+APIEXTRA));
469         if (!pktin.data)
470             fatalbox("Out of memory");
471     }
472
473     /*
474      * Read and decrypt the remainder of the packet.
475      */
476     for (i = cipherblk; i < packetlen + maclen; i++) {
477         while ((*datalen) == 0)
478             crReturn(packetlen + maclen - i);
479         pktin.data[i] = *(*data)++;
480         (*datalen)--;
481     }
482     /* Decrypt everything _except_ the MAC. */
483     if (sccipher)
484         sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
485
486 #if 0
487     debug(("Got packet len=%d pad=%d\r\n", len, pad));
488     for (i = 0; i < packetlen; i++)
489         debug(("  %02x", (unsigned char)pktin.data[i]));
490     debug(("\r\n"));
491 #endif
492
493     /*
494      * Check the MAC.
495      */
496     if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
497         fatalbox("Incorrect MAC received on packet");
498     incoming_sequence++;               /* whether or not we MACed */
499
500     pktin.savedpos = 6;
501     pktin.type = pktin.data[5];
502
503     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
504         goto next_packet;              /* FIXME: print DEBUG message */
505
506     crFinish(0);
507 }
508
509 static void ssh_gotdata(unsigned char *data, int datalen)
510 {
511     while (datalen > 0) {
512         if ( s_rdpkt(&data, &datalen) == 0 ) {
513             ssh_protocol(NULL, 0, 1);
514             if (ssh_state == SSH_STATE_CLOSED) {
515                 return;
516             }
517         }
518     }
519 }
520
521
522 static void s_wrpkt_start(int type, int len) {
523     int pad, biglen;
524
525     len += 5;                          /* type and CRC */
526     pad = 8 - (len%8);
527     biglen = len + pad;
528
529     pktout.length = len-5;
530     if (pktout.maxlen < biglen) {
531         pktout.maxlen = biglen;
532 #ifdef MSCRYPTOAPI
533         /* Allocate enough buffer space for extra block
534          * for MS CryptEncrypt() */
535         pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
536                        realloc(pktout.data, biglen+12));
537 #else
538         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
539                        realloc(pktout.data, biglen+4));
540 #endif
541         if (!pktout.data)
542             fatalbox("Out of memory");
543     }
544
545     pktout.type = type;
546     pktout.body = pktout.data+4+pad+1;
547 }
548
549 static void s_wrpkt(void) {
550     int pad, len, biglen, i;
551     unsigned long crc;
552
553     len = pktout.length + 5;           /* type and CRC */
554     pad = 8 - (len%8);
555     biglen = len + pad;
556
557     pktout.body[-1] = pktout.type;
558     for (i=0; i<pad; i++)
559         pktout.data[i+4] = random_byte();
560     crc = crc32(pktout.data+4, biglen-4);
561     PUT_32BIT(pktout.data+biglen, crc);
562     PUT_32BIT(pktout.data, len);
563
564     if (cipher)
565         cipher->encrypt(pktout.data+4, biglen);
566
567     s_write(pktout.data, biglen+4);
568 }
569
570 /*
571  * Construct a packet with the specified contents and
572  * send it to the server.
573  */
574 static void send_packet(int pkttype, ...)
575 {
576     va_list args;
577     unsigned char *p, *argp, argchar;
578     unsigned long argint;
579     int pktlen, argtype, arglen;
580     Bignum bn;
581
582     pktlen = 0;
583     va_start(args, pkttype);
584     while ((argtype = va_arg(args, int)) != PKT_END) {
585         switch (argtype) {
586           case PKT_INT:
587             (void) va_arg(args, int);
588             pktlen += 4;
589             break;
590           case PKT_CHAR:
591             (void) va_arg(args, char);
592             pktlen++;
593             break;
594           case PKT_DATA:
595             (void) va_arg(args, unsigned char *);
596             arglen = va_arg(args, int);
597             pktlen += arglen;
598             break;
599           case PKT_STR:
600             argp = va_arg(args, unsigned char *);
601             arglen = strlen(argp);
602             pktlen += 4 + arglen;
603             break;
604           case PKT_BIGNUM:
605             bn = va_arg(args, Bignum);
606             pktlen += ssh1_bignum_length(bn);
607             break;
608           default:
609             assert(0);
610         }
611     }
612     va_end(args);
613
614     s_wrpkt_start(pkttype, pktlen);
615     p = pktout.body;
616
617     va_start(args, pkttype);
618     while ((argtype = va_arg(args, int)) != PKT_END) {
619         switch (argtype) {
620           case PKT_INT:
621             argint = va_arg(args, int);
622             PUT_32BIT(p, argint);
623             p += 4;
624             break;
625           case PKT_CHAR:
626             argchar = va_arg(args, unsigned char);
627             *p = argchar;
628             p++;
629             break;
630           case PKT_DATA:
631             argp = va_arg(args, unsigned char *);
632             arglen = va_arg(args, int);
633             memcpy(p, argp, arglen);
634             p += arglen;
635             break;
636           case PKT_STR:
637             argp = va_arg(args, unsigned char *);
638             arglen = strlen(argp);
639             PUT_32BIT(p, arglen);
640             memcpy(p + 4, argp, arglen);
641             p += 4 + arglen;
642             break;
643           case PKT_BIGNUM:
644             bn = va_arg(args, Bignum);
645             p += ssh1_write_bignum(p, bn);
646             break;
647         }
648     }
649     va_end(args);
650
651     s_wrpkt();
652 }
653
654
655 /*
656  * Connect to specified host and port.
657  * Returns an error message, or NULL on success.
658  * Also places the canonical host name into `realhost'.
659  */
660 static char *connect_to_host(char *host, int port, char **realhost)
661 {
662     SOCKADDR_IN addr;
663     struct hostent *h;
664     unsigned long a;
665 #ifdef FWHACK
666     char *FWhost;
667     int FWport;
668 #endif
669
670     savedhost = malloc(1+strlen(host));
671     if (!savedhost)
672         fatalbox("Out of memory");
673     strcpy(savedhost, host);
674
675     if (port < 0)
676         port = 22;                     /* default ssh port */
677
678 #ifdef FWHACK
679     FWhost = host;
680     FWport = port;
681     host = FWSTR;
682     port = 23;
683 #endif
684
685     /*
686      * Try to find host.
687      */
688     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
689         if ( (h = gethostbyname(host)) == NULL)
690             switch (WSAGetLastError()) {
691               case WSAENETDOWN: return "Network is down";
692               case WSAHOST_NOT_FOUND: case WSANO_DATA:
693                 return "Host does not exist";
694               case WSATRY_AGAIN: return "Host not found";
695               default: return "gethostbyname: unknown error";
696             }
697         memcpy (&a, h->h_addr, sizeof(a));
698         *realhost = h->h_name;
699     } else
700         *realhost = host;
701 #ifdef FWHACK
702     *realhost = FWhost;
703 #endif
704     a = ntohl(a);
705
706     /*
707      * Open socket.
708      */
709     s = socket(AF_INET, SOCK_STREAM, 0);
710     if (s == INVALID_SOCKET)
711         switch (WSAGetLastError()) {
712           case WSAENETDOWN: return "Network is down";
713           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
714           default: return "socket(): unknown error";
715         }
716
717     /*
718      * Bind to local address.
719      */
720     addr.sin_family = AF_INET;
721     addr.sin_addr.s_addr = htonl(INADDR_ANY);
722     addr.sin_port = htons(0);
723     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
724         switch (WSAGetLastError()) {
725           case WSAENETDOWN: return "Network is down";
726           default: return "bind(): unknown error";
727         }
728
729     /*
730      * Connect to remote address.
731      */
732     addr.sin_addr.s_addr = htonl(a);
733     addr.sin_port = htons((short)port);
734     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
735         switch (WSAGetLastError()) {
736           case WSAENETDOWN: return "Network is down";
737           case WSAECONNREFUSED: return "Connection refused";
738           case WSAENETUNREACH: return "Network is unreachable";
739           case WSAEHOSTUNREACH: return "No route to host";
740           default: return "connect(): unknown error";
741         }
742
743 #ifdef FWHACK
744     send(s, "connect ", 8, 0);
745     send(s, FWhost, strlen(FWhost), 0);
746     {
747         char buf[20];
748         sprintf(buf, " %d\n", FWport);
749         send (s, buf, strlen(buf), 0);
750     }
751 #endif
752
753     return NULL;
754 }
755
756 static int ssh_versioncmp(char *a, char *b) {
757     char *ae, *be;
758     unsigned long av, bv;
759
760     av = strtoul(a, &ae, 10);
761     bv = strtoul(b, &be, 10);
762     if (av != bv) return (av < bv ? -1 : +1);
763     if (*ae == '.') ae++;
764     if (*be == '.') be++;
765     av = strtoul(ae, &ae, 10);
766     bv = strtoul(be, &be, 10);
767     if (av != bv) return (av < bv ? -1 : +1);
768     return 0;
769 }
770
771
772 /*
773  * Utility routine for putting an SSH-protocol `string' into a SHA
774  * state.
775  */
776 #include <stdio.h>
777 void sha_string(SHA_State *s, void *str, int len) {
778     unsigned char lenblk[4];
779     PUT_32BIT(lenblk, len);
780     SHA_Bytes(s, lenblk, 4);
781     SHA_Bytes(s, str, len);
782 }
783
784 /*
785  * SSH2 packet construction functions.
786  */
787 void ssh2_pkt_adddata(void *data, int len) {
788     pktout.length += len;
789     if (pktout.maxlen < pktout.length) {
790         pktout.maxlen = pktout.length + 256;
791         pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
792                        realloc(pktout.data, pktout.maxlen+APIEXTRA));
793         if (!pktout.data)
794             fatalbox("Out of memory");
795     }
796     memcpy(pktout.data+pktout.length-len, data, len);
797 }
798 void ssh2_pkt_addbyte(unsigned char byte) {
799     ssh2_pkt_adddata(&byte, 1);
800 }
801 void ssh2_pkt_init(int pkt_type) {
802     pktout.length = 5;
803     ssh2_pkt_addbyte((unsigned char)pkt_type);
804 }
805 void ssh2_pkt_addbool(unsigned char value) {
806     ssh2_pkt_adddata(&value, 1);
807 }
808 void ssh2_pkt_adduint32(unsigned long value) {
809     unsigned char x[4];
810     PUT_32BIT(x, value);
811     ssh2_pkt_adddata(x, 4);
812 }
813 void ssh2_pkt_addstring_start(void) {
814     ssh2_pkt_adduint32(0);
815     pktout.savedpos = pktout.length;
816 }
817 void ssh2_pkt_addstring_str(char *data) {
818     ssh2_pkt_adddata(data, strlen(data));
819     PUT_32BIT(pktout.data + pktout.savedpos - 4,
820               pktout.length - pktout.savedpos);
821 }
822 void ssh2_pkt_addstring_data(char *data, int len) {
823     ssh2_pkt_adddata(data, len);
824     PUT_32BIT(pktout.data + pktout.savedpos - 4,
825               pktout.length - pktout.savedpos);
826 }
827 void ssh2_pkt_addstring(char *data) {
828     ssh2_pkt_addstring_start();
829     ssh2_pkt_addstring_str(data);
830 }
831 char *ssh2_mpint_fmt(Bignum b, int *len) {
832     unsigned char *p;
833     int i, n = b[0];
834     p = malloc(n * 2 + 1);
835     if (!p)
836         fatalbox("out of memory");
837     p[0] = 0;
838     for (i = 0; i < n; i++) {
839         p[i*2+1] = (b[n-i] >> 8) & 0xFF;
840         p[i*2+2] = (b[n-i]     ) & 0xFF;
841     }
842     i = 0;
843     while (p[i] == 0 && (p[i+1] & 0x80) == 0)
844         i++;
845     memmove(p, p+i, n*2+1-i);
846     *len = n*2+1-i;
847     return p;
848 }
849 void ssh2_pkt_addmp(Bignum b) {
850     unsigned char *p;
851     int len;
852     p = ssh2_mpint_fmt(b, &len);
853     ssh2_pkt_addstring_start();
854     ssh2_pkt_addstring_data(p, len);
855     free(p);
856 }
857 void ssh2_pkt_send(void) {
858     int cipherblk, maclen, padding, i;
859     static unsigned long outgoing_sequence = 0;
860
861     /*
862      * Add padding. At least four bytes, and must also bring total
863      * length (minus MAC) up to a multiple of the block size.
864      */
865     cipherblk = cipher ? cipher->blksize : 8;   /* block size */
866     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
867     padding = 4;
868     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
869     pktout.data[4] = padding;
870     for (i = 0; i < padding; i++)
871         pktout.data[pktout.length + i] = random_byte();
872     PUT_32BIT(pktout.data, pktout.length + padding - 4);
873     if (csmac)
874         csmac->generate(pktout.data, pktout.length + padding,
875                         outgoing_sequence);
876     outgoing_sequence++;               /* whether or not we MACed */
877
878 #if 0
879     debug(("Sending packet len=%d\r\n", pktout.length+padding));
880     for (i = 0; i < pktout.length+padding; i++)
881         debug(("  %02x", (unsigned char)pktout.data[i]));
882     debug(("\r\n"));
883 #endif
884
885     if (cscipher)
886         cscipher->encrypt(pktout.data, pktout.length + padding);
887     maclen = csmac ? csmac->len : 0;
888
889     s_write(pktout.data, pktout.length + padding + maclen);
890 }
891
892 #if 0
893 void bndebug(char *string, Bignum b) {
894     unsigned char *p;
895     int i, len;
896     p = ssh2_mpint_fmt(b, &len);
897     debug(("%s", string));
898     for (i = 0; i < len; i++)
899         debug((" %02x", p[i]));
900     debug(("\r\n"));
901     free(p);
902 }
903 #endif
904
905 void sha_mpint(SHA_State *s, Bignum b) {
906     unsigned char *p;
907     int len;
908     p = ssh2_mpint_fmt(b, &len);
909     sha_string(s, p, len);
910     free(p);
911 }
912
913 /*
914  * SSH2 packet decode functions.
915  */
916 unsigned long ssh2_pkt_getuint32(void) {
917     unsigned long value;
918     if (pktin.length - pktin.savedpos < 4)
919         return 0;                      /* arrgh, no way to decline (FIXME?) */
920     value = GET_32BIT(pktin.data+pktin.savedpos);
921     pktin.savedpos += 4;
922     return value;
923 }
924 void ssh2_pkt_getstring(char **p, int *length) {
925     *p = NULL;
926     if (pktin.length - pktin.savedpos < 4)
927         return;
928     *length = GET_32BIT(pktin.data+pktin.savedpos);
929     pktin.savedpos += 4;
930     if (pktin.length - pktin.savedpos < *length)
931         return;
932     *p = pktin.data+pktin.savedpos;
933     pktin.savedpos += *length;
934 }
935 Bignum ssh2_pkt_getmp(void) {
936     char *p;
937     int i, j, length;
938     Bignum b;
939
940     ssh2_pkt_getstring(&p, &length);
941     if (!p)
942         return NULL;
943     if (p[0] & 0x80)
944         fatalbox("internal error: Can't handle negative mpints");
945     b = newbn((length+1)/2);
946     for (i = 0; i < length; i++) {
947         j = length - 1 - i;
948         if (j & 1)
949             b[j/2+1] |= ((unsigned char)p[i]) << 8;
950         else
951             b[j/2+1] |= ((unsigned char)p[i]);
952     }
953     return b;
954 }
955
956 static int do_ssh_init(void) {
957     char c, *vsp;
958     char version[10];
959     char vstring[80];
960     char vlog[sizeof(vstring)+20];
961     int i;
962
963 #ifdef FWHACK
964     i = 0;
965     while (s_read(&c, 1) == 1) {
966         if (c == 'S' && i < 2) i++;
967         else if (c == 'S' && i == 2) i = 2;
968         else if (c == 'H' && i == 2) break;
969         else i = 0;
970     }
971 #else
972     if (s_read(&c,1) != 1 || c != 'S') return 0;
973     if (s_read(&c,1) != 1 || c != 'S') return 0;
974     if (s_read(&c,1) != 1 || c != 'H') return 0;
975 #endif
976     strcpy(vstring, "SSH-");
977     vsp = vstring+4;
978     if (s_read(&c,1) != 1 || c != '-') return 0;
979     i = 0;
980     while (1) {
981         if (s_read(&c,1) != 1)
982             return 0;
983         if (vsp < vstring+sizeof(vstring)-1)
984             *vsp++ = c;
985         if (i >= 0) {
986             if (c == '-') {
987                 version[i] = '\0';
988                 i = -1;
989             } else if (i < sizeof(version)-1)
990                 version[i++] = c;
991         }
992         else if (c == '\n')
993             break;
994     }
995
996     *vsp = 0;
997     sprintf(vlog, "Server version: %s", vstring);
998     vlog[strcspn(vlog, "\r\n")] = '\0';
999     logevent(vlog);
1000
1001     /*
1002      * Server version "1.99" means we can choose whether we use v1
1003      * or v2 protocol. Choice is based on cfg.sshprot.
1004      */
1005     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1006         /*
1007          * This is a v2 server. Begin v2 protocol.
1008          */
1009         char *verstring = "SSH-2.0-PuTTY";
1010         SHA_Init(&exhash);
1011         /*
1012          * Hash our version string and their version string.
1013          */
1014         sha_string(&exhash, verstring, strlen(verstring));
1015         sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
1016         sprintf(vstring, "%s\n", verstring);
1017         sprintf(vlog, "We claim version: %s", verstring);
1018         logevent(vlog);
1019         logevent("Using SSH protocol version 2");
1020         s_write(vstring, strlen(vstring));
1021         ssh_protocol = ssh2_protocol;
1022         ssh_version = 2;
1023         s_rdpkt = ssh2_rdpkt;
1024     } else {
1025         /*
1026          * This is a v1 server. Begin v1 protocol.
1027          */
1028         sprintf(vstring, "SSH-%s-PuTTY\n",
1029                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1030         sprintf(vlog, "We claim version: %s", vstring);
1031         vlog[strcspn(vlog, "\r\n")] = '\0';
1032         logevent(vlog);
1033         logevent("Using SSH protocol version 1");
1034         s_write(vstring, strlen(vstring));
1035         ssh_protocol = ssh1_protocol;
1036         ssh_version = 1;
1037         s_rdpkt = ssh1_rdpkt;
1038     }
1039     ssh_send_ok = 0;
1040     return 1;
1041 }
1042
1043 /*
1044  * Handle the key exchange and user authentication phases.
1045  */
1046 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1047 {
1048     int i, j, len;
1049     unsigned char *rsabuf, *keystr1, *keystr2;
1050     unsigned char cookie[8];
1051     struct RSAKey servkey, hostkey;
1052     struct MD5Context md5c;
1053     static unsigned long supported_ciphers_mask, supported_auths_mask;
1054     static int tried_publickey;
1055     static unsigned char session_id[16];
1056     int cipher_type;
1057
1058     crBegin;
1059
1060     if (!ispkt) crWaitUntil(ispkt);
1061
1062     if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1063         fatalbox("Public key packet not received");
1064
1065     logevent("Received public keys");
1066
1067     memcpy(cookie, pktin.body, 8);
1068
1069     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1070     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1071
1072     /*
1073      * Hash the host key and print the hash in the log box. Just as
1074      * a last resort in case the registry's host key checking is
1075      * compromised, we'll allow the user some ability to verify
1076      * host keys by eye.
1077      */
1078     MD5Init(&md5c);
1079     MD5Update(&md5c, keystr2, hostkey.bytes);
1080     MD5Final(session_id, &md5c);
1081     {
1082         char logmsg[80];
1083         int i;
1084         logevent("Host key MD5 is:");
1085         strcpy(logmsg, "      ");
1086         for (i = 0; i < 16; i++)
1087             sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1088         logevent(logmsg);
1089     }
1090
1091     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1092     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1093
1094     MD5Init(&md5c);
1095     MD5Update(&md5c, keystr2, hostkey.bytes);
1096     MD5Update(&md5c, keystr1, servkey.bytes);
1097     MD5Update(&md5c, pktin.body, 8);
1098     MD5Final(session_id, &md5c);
1099
1100     for (i=0; i<32; i++)
1101         session_key[i] = random_byte();
1102
1103     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1104
1105     rsabuf = malloc(len);
1106     if (!rsabuf)
1107         fatalbox("Out of memory");
1108
1109     /*
1110      * Verify the host key.
1111      */
1112     {
1113         /*
1114          * First format the key into a string.
1115          */
1116         int len = rsastr_len(&hostkey);
1117         char *keystr = malloc(len);
1118         if (!keystr)
1119             fatalbox("Out of memory");
1120         rsastr_fmt(keystr, &hostkey);
1121         verify_ssh_host_key(savedhost, keystr);
1122         free(keystr);
1123     }
1124
1125     for (i=0; i<32; i++) {
1126         rsabuf[i] = session_key[i];
1127         if (i < 16)
1128             rsabuf[i] ^= session_id[i];
1129     }
1130
1131     if (hostkey.bytes > servkey.bytes) {
1132         rsaencrypt(rsabuf, 32, &servkey);
1133         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1134     } else {
1135         rsaencrypt(rsabuf, 32, &hostkey);
1136         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1137     }
1138
1139     logevent("Encrypted session key");
1140
1141     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1142                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
1143                   SSH_CIPHER_3DES;
1144     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1145         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1146         cipher_type = SSH_CIPHER_3DES;
1147     }
1148     switch (cipher_type) {
1149       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1150       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1151       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1152     }
1153
1154     send_packet(SSH1_CMSG_SESSION_KEY,
1155                 PKT_CHAR, cipher_type,
1156                 PKT_DATA, cookie, 8,
1157                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1158                 PKT_DATA, rsabuf, len,
1159                 PKT_INT, 0,
1160                 PKT_END);
1161
1162     logevent("Trying to enable encryption...");
1163
1164     free(rsabuf);
1165
1166     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1167              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1168              &ssh_3des;
1169     cipher->sesskey(session_key);
1170
1171     crWaitUntil(ispkt);
1172
1173     if (pktin.type != SSH1_SMSG_SUCCESS)
1174         fatalbox("Encryption not successfully enabled");
1175
1176     logevent("Successfully started encryption");
1177
1178     fflush(stdout);
1179     {
1180         static char username[100];
1181         static int pos = 0;
1182         static char c;
1183         if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1184             c_write("login as: ", 10);
1185             while (pos >= 0) {
1186                 crWaitUntil(!ispkt);
1187                 while (inlen--) switch (c = *in++) {
1188                   case 10: case 13:
1189                     username[pos] = 0;
1190                     pos = -1;
1191                     break;
1192                   case 8: case 127:
1193                     if (pos > 0) {
1194                         c_write("\b \b", 3);
1195                         pos--;
1196                     }
1197                     break;
1198                   case 21: case 27:
1199                     while (pos > 0) {
1200                         c_write("\b \b", 3);
1201                         pos--;
1202                     }
1203                     break;
1204                   case 3: case 4:
1205                     random_save_seed();
1206                     exit(0);
1207                     break;
1208                   default:
1209                     if (((c >= ' ' && c <= '~') ||
1210                          ((unsigned char)c >= 160)) && pos < 40) {
1211                         username[pos++] = c;
1212                         c_write(&c, 1);
1213                     }
1214                     break;
1215                 }
1216             }
1217             c_write("\r\n", 2);
1218             username[strcspn(username, "\n\r")] = '\0';
1219         } else {
1220             char stuff[200];
1221             strncpy(username, cfg.username, 99);
1222             username[99] = '\0';
1223             if (flags & FLAG_VERBOSE) {
1224                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1225                 c_write(stuff, strlen(stuff));
1226             }
1227         }
1228
1229         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1230         {
1231             char userlog[20+sizeof(username)];
1232             sprintf(userlog, "Sent username \"%s\"", username);
1233             logevent(userlog);
1234         }
1235     }
1236
1237     crWaitUntil(ispkt);
1238
1239     tried_publickey = 0;
1240
1241     while (pktin.type == SSH1_SMSG_FAILURE) {
1242         static char password[100];
1243         static int pos;
1244         static char c;
1245         static int pwpkt_type;
1246         /*
1247          * Show password prompt, having first obtained it via a TIS
1248          * or CryptoCard exchange if we're doing TIS or CryptoCard
1249          * authentication.
1250          */
1251         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1252         if (agent_exists()) {
1253             /*
1254              * Attempt RSA authentication using Pageant.
1255              */
1256             static unsigned char request[5], *response, *p;
1257             static int responselen;
1258             static int i, nkeys;
1259             static int authed = FALSE;
1260             void *r;
1261
1262             logevent("Pageant is running. Requesting keys.");
1263
1264             /* Request the keys held by the agent. */
1265             PUT_32BIT(request, 1);
1266             request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1267             agent_query(request, 5, &r, &responselen);
1268             response = (unsigned char *)r;
1269             if (response) {
1270                 p = response + 5;
1271                 nkeys = GET_32BIT(p); p += 4;
1272                 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1273                     logevent(buf); }
1274                 for (i = 0; i < nkeys; i++) {
1275                     static struct RSAKey key;
1276                     static Bignum challenge;
1277                     static char *commentp;
1278                     static int commentlen;
1279
1280                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1281                         logevent(buf); }
1282                     p += 4;
1283                     p += ssh1_read_bignum(p, &key.exponent);
1284                     p += ssh1_read_bignum(p, &key.modulus);
1285                     commentlen = GET_32BIT(p); p += 4;
1286                     commentp = p; p += commentlen;
1287                     send_packet(SSH1_CMSG_AUTH_RSA,
1288                                 PKT_BIGNUM, key.modulus, PKT_END);
1289                     crWaitUntil(ispkt);
1290                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1291                         logevent("Key refused");
1292                         continue;
1293                     }
1294                     logevent("Received RSA challenge");
1295                     ssh1_read_bignum(pktin.body, &challenge);
1296                     {
1297                         char *agentreq, *q, *ret;
1298                         int len, retlen;
1299                         len = 1 + 4;   /* message type, bit count */
1300                         len += ssh1_bignum_length(key.exponent);
1301                         len += ssh1_bignum_length(key.modulus);
1302                         len += ssh1_bignum_length(challenge);
1303                         len += 16;     /* session id */
1304                         len += 4;      /* response format */
1305                         agentreq = malloc(4 + len);
1306                         PUT_32BIT(agentreq, len);
1307                         q = agentreq + 4;
1308                         *q++ = SSH_AGENTC_RSA_CHALLENGE;
1309                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1310                         q += 4;
1311                         q += ssh1_write_bignum(q, key.exponent);
1312                         q += ssh1_write_bignum(q, key.modulus);
1313                         q += ssh1_write_bignum(q, challenge);
1314                         memcpy(q, session_id, 16); q += 16;
1315                         PUT_32BIT(q, 1);   /* response format */
1316                         agent_query(agentreq, len+4, &ret, &retlen);
1317                         free(agentreq);
1318                         if (ret) {
1319                             if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1320                                 logevent("Sending Pageant's response");
1321                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1322                                             PKT_DATA, ret+5, 16, PKT_END);
1323                                 free(ret);
1324                                 crWaitUntil(ispkt);
1325                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1326                                     logevent("Pageant's response accepted");
1327                                     c_write("Authenticated using RSA key \"",
1328                                             29);
1329                                     c_write(commentp, commentlen);
1330                                     c_write("\" from agent\r\n", 14);
1331                                     authed = TRUE;
1332                                 } else
1333                                     logevent("Pageant's response not accepted");
1334                             } else {
1335                                 logevent("Pageant failed to answer challenge");
1336                                 free(ret);
1337                             }
1338                         } else {
1339                             logevent("No reply received from Pageant");
1340                         }
1341                     }
1342                     freebn(key.exponent);
1343                     freebn(key.modulus);
1344                     freebn(challenge);
1345                     if (authed)
1346                         break;
1347                 }
1348             }
1349             if (authed)
1350                 break;
1351         }
1352         if (*cfg.keyfile && !tried_publickey)
1353             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1354
1355         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1356             char prompt[200];
1357             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1358             if (!ssh_get_password(prompt, password, sizeof(password))) {
1359                 /*
1360                  * get_password failed to get a password (for
1361                  * example because one was supplied on the command
1362                  * line which has already failed to work).
1363                  * Terminate.
1364                  */
1365                 logevent("No more passwords to try");
1366                 ssh_state = SSH_STATE_CLOSED;
1367                 crReturn(1);
1368             }
1369         } else {
1370
1371             if (pktin.type == SSH1_SMSG_FAILURE &&
1372                 cfg.try_tis_auth &&
1373                 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1374                 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1375                 logevent("Requested TIS authentication");
1376                 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1377                 crWaitUntil(ispkt);
1378                 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1379                     logevent("TIS authentication declined");
1380                     c_write("TIS authentication refused.\r\n", 29);
1381                 } else {
1382                     int challengelen = ((pktin.body[0] << 24) |
1383                                         (pktin.body[1] << 16) |
1384                                         (pktin.body[2] << 8) |
1385                                         (pktin.body[3]));
1386                     logevent("Received TIS challenge");
1387                     c_write(pktin.body+4, challengelen);
1388                 }
1389             }
1390             if (pktin.type == SSH1_SMSG_FAILURE &&
1391                 cfg.try_tis_auth &&
1392                 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1393                 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1394                 logevent("Requested CryptoCard authentication");
1395                 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1396                 crWaitUntil(ispkt);
1397                 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1398                     logevent("CryptoCard authentication declined");
1399                     c_write("CryptoCard authentication refused.\r\n", 29);
1400                 } else {
1401                     int challengelen = ((pktin.body[0] << 24) |
1402                                         (pktin.body[1] << 16) |
1403                                         (pktin.body[2] << 8) |
1404                                         (pktin.body[3]));
1405                     logevent("Received CryptoCard challenge");
1406                     c_write(pktin.body+4, challengelen);
1407                     c_write("\r\nResponse : ", 13);
1408                 }
1409             }
1410             if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1411                 c_write("password: ", 10);
1412             if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1413                 if (flags & FLAG_VERBOSE)
1414                     c_write("Trying public key authentication.\r\n", 35);
1415                 if (!rsakey_encrypted(cfg.keyfile)) {
1416                     if (flags & FLAG_VERBOSE)
1417                         c_write("No passphrase required.\r\n", 25);
1418                     goto tryauth;
1419                 }
1420                 c_write("passphrase: ", 12);
1421             }
1422
1423             pos = 0;
1424             while (pos >= 0) {
1425                 crWaitUntil(!ispkt);
1426                 while (inlen--) switch (c = *in++) {
1427                   case 10: case 13:
1428                     password[pos] = 0;
1429                     pos = -1;
1430                     break;
1431                   case 8: case 127:
1432                     if (pos > 0)
1433                         pos--;
1434                     break;
1435                   case 21: case 27:
1436                     pos = 0;
1437                     break;
1438                   case 3: case 4:
1439                     random_save_seed();
1440                     exit(0);
1441                     break;
1442                   default:
1443                     if (((c >= ' ' && c <= '~') ||
1444                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1445                         password[pos++] = c;
1446                     break;
1447                 }
1448             }
1449             c_write("\r\n", 2);
1450
1451         }
1452
1453         tryauth:
1454         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1455             /*
1456              * Try public key authentication with the specified
1457              * key file.
1458              */
1459             static struct RSAKey pubkey;
1460             static Bignum challenge, response;
1461             static int i;
1462             static unsigned char buffer[32];
1463
1464             tried_publickey = 1;
1465             i = loadrsakey(cfg.keyfile, &pubkey, password);
1466             if (i == 0) {
1467                 c_write("Couldn't load public key from ", 30);
1468                 c_write(cfg.keyfile, strlen(cfg.keyfile));
1469                 c_write(".\r\n", 3);
1470                 continue;              /* go and try password */
1471             }
1472             if (i == -1) {
1473                 c_write("Wrong passphrase.\r\n", 19);
1474                 tried_publickey = 0;
1475                 continue;              /* try again */
1476             }
1477
1478             /*
1479              * Send a public key attempt.
1480              */
1481             send_packet(SSH1_CMSG_AUTH_RSA,
1482                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1483
1484             crWaitUntil(ispkt);
1485             if (pktin.type == SSH1_SMSG_FAILURE) {
1486                 if (flags & FLAG_VERBOSE)
1487                     c_write("Server refused our public key.\r\n", 32);
1488                 continue;              /* go and try password */
1489             }
1490             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1491                 fatalbox("Bizarre response to offer of public key");
1492             ssh1_read_bignum(pktin.body, &challenge);
1493             response = rsadecrypt(challenge, &pubkey);
1494             freebn(pubkey.private_exponent);   /* burn the evidence */
1495
1496             for (i = 0; i < 32; i += 2) {
1497                 buffer[i] = response[16-i/2] >> 8;
1498                 buffer[i+1] = response[16-i/2] & 0xFF;
1499             }
1500
1501             MD5Init(&md5c);
1502             MD5Update(&md5c, buffer, 32);
1503             MD5Update(&md5c, session_id, 16);
1504             MD5Final(buffer, &md5c);
1505
1506             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1507                         PKT_DATA, buffer, 16, PKT_END);
1508
1509             crWaitUntil(ispkt);
1510             if (pktin.type == SSH1_SMSG_FAILURE) {
1511                 if (flags & FLAG_VERBOSE)
1512                     c_write("Failed to authenticate with our public key.\r\n",
1513                             45);
1514                 continue;              /* go and try password */
1515             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1516                 fatalbox("Bizarre response to RSA authentication response");
1517             }
1518
1519             break;                     /* we're through! */
1520         } else {
1521             send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1522         }
1523         logevent("Sent password");
1524         memset(password, 0, strlen(password));
1525         crWaitUntil(ispkt);
1526         if (pktin.type == SSH1_SMSG_FAILURE) {
1527             if (flags & FLAG_VERBOSE)
1528                 c_write("Access denied\r\n", 15);
1529             logevent("Authentication refused");
1530         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1531             logevent("Received disconnect request");
1532             ssh_state = SSH_STATE_CLOSED;
1533             crReturn(1);
1534         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1535             fatalbox("Strange packet received, type %d", pktin.type);
1536         }
1537     }
1538
1539     logevent("Authentication successful");
1540
1541     crFinish(1);
1542 }
1543
1544 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1545     crBegin;
1546
1547     random_init();
1548
1549     while (!do_ssh1_login(in, inlen, ispkt)) {
1550         crReturnV;
1551     }
1552     if (ssh_state == SSH_STATE_CLOSED)
1553         crReturnV;
1554
1555     if (cfg.agentfwd && agent_exists()) {
1556         logevent("Requesting agent forwarding");
1557         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1558         do { crReturnV; } while (!ispkt);
1559         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1560             fatalbox("Protocol confusion");
1561         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1562             logevent("Agent forwarding refused");
1563         } else
1564             logevent("Agent forwarding enabled");
1565     }
1566
1567     if (!cfg.nopty) {
1568         send_packet(SSH1_CMSG_REQUEST_PTY,
1569                     PKT_STR, cfg.termtype,
1570                     PKT_INT, rows, PKT_INT, cols,
1571                     PKT_INT, 0, PKT_INT, 0,
1572                     PKT_CHAR, 0,
1573                     PKT_END);
1574         ssh_state = SSH_STATE_INTERMED;
1575         do { crReturnV; } while (!ispkt);
1576         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1577             fatalbox("Protocol confusion");
1578         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1579             c_write("Server refused to allocate pty\r\n", 32);
1580         }
1581         logevent("Allocated pty");
1582     }
1583
1584     if (*cfg.remote_cmd)
1585         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1586     else
1587         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1588     logevent("Started session");
1589
1590     ssh_state = SSH_STATE_SESSION;
1591     if (size_needed)
1592         ssh_size();
1593
1594     ssh_send_ok = 1;
1595     ssh_channels = newtree234(ssh_channelcmp);
1596     while (1) {
1597         crReturnV;
1598         if (ispkt) {
1599             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1600                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1601                 long len = GET_32BIT(pktin.body);
1602                 c_write(pktin.body+4, len);
1603             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1604                 ssh_state = SSH_STATE_CLOSED;
1605                 logevent("Received disconnect request");
1606             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1607                 /* Remote side is trying to open a channel to talk to our
1608                  * agent. Give them back a local channel number. */
1609                 unsigned i = 1;
1610                 struct ssh_channel *c;
1611                 enum234 e;
1612                 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1613                     if (c->localid > i)
1614                         break;         /* found a free number */
1615                     i = c->localid + 1;
1616                 }
1617                 c = malloc(sizeof(struct ssh_channel));
1618                 c->remoteid = GET_32BIT(pktin.body);
1619                 c->localid = i;
1620                 c->closes = 0;
1621                 c->type = SSH1_SMSG_AGENT_OPEN;   /* identify channel type */
1622                 add234(ssh_channels, c);
1623                 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1624                             PKT_INT, c->remoteid, PKT_INT, c->localid,
1625                             PKT_END);
1626             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1627                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1628                 /* Remote side closes a channel. */
1629                 unsigned i = GET_32BIT(pktin.body);
1630                 struct ssh_channel *c;
1631                 c = find234(ssh_channels, &i, ssh_channelfind);
1632                 if (c) {
1633                     int closetype;
1634                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1635                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1636                     c->closes |= closetype;
1637                     if (c->closes == 3) {
1638                         del234(ssh_channels, c);
1639                         free(c);
1640                     }
1641                 }
1642             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1643                 /* Data sent down one of our channels. */
1644                 int i = GET_32BIT(pktin.body);
1645                 int len = GET_32BIT(pktin.body+4);
1646                 unsigned char *p = pktin.body+8;
1647                 struct ssh_channel *c;
1648                 c = find234(ssh_channels, &i, ssh_channelfind);
1649                 if (c) {
1650                     switch(c->type) {
1651                       case SSH1_SMSG_AGENT_OPEN:
1652                         /* Data for an agent message. Buffer it. */
1653                         while (len > 0) {
1654                             if (c->u.a.lensofar < 4) {
1655                                 int l = min(4 - c->u.a.lensofar, len);
1656                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1657                                 p += l; len -= l; c->u.a.lensofar += l;
1658                             }
1659                             if (c->u.a.lensofar == 4) {
1660                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1661                                 c->u.a.message = malloc(c->u.a.totallen);
1662                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
1663                             }
1664                             if (c->u.a.lensofar >= 4 && len > 0) {
1665                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1666                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1667                                 p += l; len -= l; c->u.a.lensofar += l;
1668                             }
1669                             if (c->u.a.lensofar == c->u.a.totallen) {
1670                                 void *reply, *sentreply;
1671                                 int replylen;
1672                                 agent_query(c->u.a.message, c->u.a.totallen,
1673                                             &reply, &replylen);
1674                                 if (reply)
1675                                     sentreply = reply;
1676                                 else {
1677                                     /* Fake SSH_AGENT_FAILURE. */
1678                                     sentreply = "\0\0\0\1\5";
1679                                     replylen = 5;
1680                                 }
1681                                 send_packet(SSH1_MSG_CHANNEL_DATA,
1682                                             PKT_INT, c->remoteid,
1683                                             PKT_INT, replylen,
1684                                             PKT_DATA, sentreply, replylen,
1685                                             PKT_END);
1686                                 if (reply)
1687                                     free(reply);
1688                                 free(c->u.a.message);
1689                                 c->u.a.lensofar = 0;
1690                             }
1691                         }
1692                         break;
1693                     }
1694                 }                
1695             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1696                 /* may be from EXEC_SHELL on some servers */
1697             } else if (pktin.type == SSH1_SMSG_FAILURE) {
1698                 /* may be from EXEC_SHELL on some servers
1699                  * if no pty is available or in other odd cases. Ignore */
1700             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1701                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1702             } else {
1703                 fatalbox("Strange packet received: type %d", pktin.type);
1704             }
1705         } else {
1706             send_packet(SSH1_CMSG_STDIN_DATA,
1707                         PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1708         }
1709     }
1710
1711     crFinishV;
1712 }
1713
1714 /*
1715  * Utility routine for decoding comma-separated strings in KEXINIT.
1716  */
1717 int in_commasep_string(char *needle, char *haystack, int haylen) {
1718     int needlen = strlen(needle);
1719     while (1) {
1720         /*
1721          * Is it at the start of the string?
1722          */
1723         if (haylen >= needlen &&       /* haystack is long enough */
1724             !memcmp(needle, haystack, needlen) &&    /* initial match */
1725             (haylen == needlen || haystack[needlen] == ',')
1726                                        /* either , or EOS follows */
1727             )
1728             return 1;
1729         /*
1730          * If not, search for the next comma and resume after that.
1731          * If no comma found, terminate.
1732          */
1733         while (haylen > 0 && *haystack != ',')
1734             haylen--, haystack++;
1735         if (haylen == 0)
1736             return 0;
1737         haylen--, haystack++;          /* skip over comma itself */
1738     }
1739 }
1740
1741 /*
1742  * SSH2 key creation method.
1743  */
1744 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1745     SHA_State s;
1746     /* First 20 bytes. */
1747     SHA_Init(&s);
1748     sha_mpint(&s, K);
1749     SHA_Bytes(&s, H, 20);
1750     SHA_Bytes(&s, &chr, 1);
1751     SHA_Bytes(&s, H, 20);
1752     SHA_Final(&s, keyspace);
1753     /* Next 20 bytes. */
1754     SHA_Init(&s);
1755     sha_mpint(&s, K);
1756     SHA_Bytes(&s, H, 20);
1757     SHA_Bytes(&s, keyspace, 20);
1758     SHA_Final(&s, keyspace+20);
1759 }
1760
1761 /*
1762  * Handle the SSH2 transport layer.
1763  */
1764 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1765 {
1766     static int i, len;
1767     static char *str;
1768     static Bignum e, f, K;
1769     static struct ssh_cipher *cscipher_tobe = NULL;
1770     static struct ssh_cipher *sccipher_tobe = NULL;
1771     static struct ssh_mac *csmac_tobe = NULL;
1772     static struct ssh_mac *scmac_tobe = NULL;
1773     static struct ssh_compress *cscomp_tobe = NULL;
1774     static struct ssh_compress *sccomp_tobe = NULL;
1775     static char *hostkeydata, *sigdata, *keystr;
1776     static int hostkeylen, siglen;
1777     static unsigned char exchange_hash[20];
1778     static unsigned char keyspace[40];
1779
1780     crBegin;
1781     random_init();
1782
1783     begin_key_exchange:
1784     /*
1785      * Construct and send our key exchange packet.
1786      */
1787     ssh2_pkt_init(SSH2_MSG_KEXINIT);
1788     for (i = 0; i < 16; i++)
1789         ssh2_pkt_addbyte((unsigned char)random_byte());
1790     /* List key exchange algorithms. */
1791     ssh2_pkt_addstring_start();
1792     for (i = 0; i < lenof(kex_algs); i++) {
1793         ssh2_pkt_addstring_str(kex_algs[i]->name);
1794         if (i < lenof(kex_algs)-1)
1795             ssh2_pkt_addstring_str(",");
1796     }
1797     /* List server host key algorithms. */
1798     ssh2_pkt_addstring_start();
1799     for (i = 0; i < lenof(hostkey_algs); i++) {
1800         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1801         if (i < lenof(hostkey_algs)-1)
1802             ssh2_pkt_addstring_str(",");
1803     }
1804     /* List client->server encryption algorithms. */
1805     ssh2_pkt_addstring_start();
1806     for (i = 0; i < lenof(ciphers); i++) {
1807         ssh2_pkt_addstring_str(ciphers[i]->name);
1808         if (i < lenof(ciphers)-1)
1809             ssh2_pkt_addstring_str(",");
1810     }
1811     /* List server->client encryption algorithms. */
1812     ssh2_pkt_addstring_start();
1813     for (i = 0; i < lenof(ciphers); i++) {
1814         ssh2_pkt_addstring_str(ciphers[i]->name);
1815         if (i < lenof(ciphers)-1)
1816             ssh2_pkt_addstring_str(",");
1817     }
1818     /* List client->server MAC algorithms. */
1819     ssh2_pkt_addstring_start();
1820     for (i = 0; i < lenof(macs); i++) {
1821         ssh2_pkt_addstring_str(macs[i]->name);
1822         if (i < lenof(macs)-1)
1823             ssh2_pkt_addstring_str(",");
1824     }
1825     /* List server->client MAC algorithms. */
1826     ssh2_pkt_addstring_start();
1827     for (i = 0; i < lenof(macs); i++) {
1828         ssh2_pkt_addstring_str(macs[i]->name);
1829         if (i < lenof(macs)-1)
1830             ssh2_pkt_addstring_str(",");
1831     }
1832     /* List client->server compression algorithms. */
1833     ssh2_pkt_addstring_start();
1834     for (i = 0; i < lenof(compressions); i++) {
1835         ssh2_pkt_addstring_str(compressions[i]->name);
1836         if (i < lenof(compressions)-1)
1837             ssh2_pkt_addstring_str(",");
1838     }
1839     /* List server->client compression algorithms. */
1840     ssh2_pkt_addstring_start();
1841     for (i = 0; i < lenof(compressions); i++) {
1842         ssh2_pkt_addstring_str(compressions[i]->name);
1843         if (i < lenof(compressions)-1)
1844             ssh2_pkt_addstring_str(",");
1845     }
1846     /* List client->server languages. Empty list. */
1847     ssh2_pkt_addstring_start();
1848     /* List server->client languages. Empty list. */
1849     ssh2_pkt_addstring_start();
1850     /* First KEX packet does _not_ follow, because we're not that brave. */
1851     ssh2_pkt_addbool(FALSE);
1852     /* Reserved. */
1853     ssh2_pkt_adduint32(0);
1854     sha_string(&exhash, pktout.data+5, pktout.length-5);
1855     ssh2_pkt_send();
1856
1857     if (!ispkt) crWaitUntil(ispkt);
1858     sha_string(&exhash, pktin.data+5, pktin.length-5);
1859
1860     /*
1861      * Now examine the other side's KEXINIT to see what we're up
1862      * to.
1863      */
1864     if (pktin.type != SSH2_MSG_KEXINIT) {
1865         fatalbox("expected key exchange packet from server");
1866     }
1867     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1868     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1869     pktin.savedpos += 16;              /* skip garbage cookie */
1870     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
1871     for (i = 0; i < lenof(kex_algs); i++) {
1872         if (in_commasep_string(kex_algs[i]->name, str, len)) {
1873             kex = kex_algs[i];
1874             break;
1875         }
1876     }
1877     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
1878     for (i = 0; i < lenof(hostkey_algs); i++) {
1879         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1880             hostkey = hostkey_algs[i];
1881             break;
1882         }
1883     }
1884     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
1885     for (i = 0; i < lenof(ciphers); i++) {
1886         if (in_commasep_string(ciphers[i]->name, str, len)) {
1887             cscipher_tobe = ciphers[i];
1888             break;
1889         }
1890     }
1891     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
1892     for (i = 0; i < lenof(ciphers); i++) {
1893         if (in_commasep_string(ciphers[i]->name, str, len)) {
1894             sccipher_tobe = ciphers[i];
1895             break;
1896         }
1897     }
1898     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
1899     for (i = 0; i < lenof(macs); i++) {
1900         if (in_commasep_string(macs[i]->name, str, len)) {
1901             csmac_tobe = macs[i];
1902             break;
1903         }
1904     }
1905     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
1906     for (i = 0; i < lenof(macs); i++) {
1907         if (in_commasep_string(macs[i]->name, str, len)) {
1908             scmac_tobe = macs[i];
1909             break;
1910         }
1911     }
1912     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
1913     for (i = 0; i < lenof(compressions); i++) {
1914         if (in_commasep_string(compressions[i]->name, str, len)) {
1915             cscomp_tobe = compressions[i];
1916             break;
1917         }
1918     }
1919     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
1920     for (i = 0; i < lenof(compressions); i++) {
1921         if (in_commasep_string(compressions[i]->name, str, len)) {
1922             sccomp_tobe = compressions[i];
1923             break;
1924         }
1925     }
1926
1927     /*
1928      * Currently we only support Diffie-Hellman and DSS, so let's
1929      * bomb out if those aren't selected.
1930      */
1931     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1932         fatalbox("internal fault: chaos in SSH 2 transport layer");
1933
1934     /*
1935      * Now we begin the fun. Generate and send e for Diffie-Hellman.
1936      */
1937     e = dh_create_e();
1938     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1939     ssh2_pkt_addmp(e);
1940     ssh2_pkt_send();
1941
1942     crWaitUntil(ispkt);
1943     if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1944         fatalbox("expected key exchange packet from server");
1945     }
1946     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1947     f = ssh2_pkt_getmp();
1948     ssh2_pkt_getstring(&sigdata, &siglen);
1949
1950     K = dh_find_K(f);
1951
1952     sha_string(&exhash, hostkeydata, hostkeylen);
1953     sha_mpint(&exhash, e);
1954     sha_mpint(&exhash, f);
1955     sha_mpint(&exhash, K);
1956     SHA_Final(&exhash, exchange_hash);
1957
1958 #if 0
1959     debug(("Exchange hash is:\r\n"));
1960     for (i = 0; i < 20; i++)
1961         debug((" %02x", exchange_hash[i]));
1962     debug(("\r\n"));
1963 #endif
1964
1965     hostkey->setkey(hostkeydata, hostkeylen);
1966     if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1967         fatalbox("Server failed host key check");
1968
1969     /*
1970      * Expect SSH2_MSG_NEWKEYS from server.
1971      */
1972     crWaitUntil(ispkt);
1973     if (pktin.type != SSH2_MSG_NEWKEYS)
1974         fatalbox("expected new-keys packet from server");
1975
1976     /*
1977      * Authenticate remote host: verify host key. (We've already
1978      * checked the signature of the exchange hash.)
1979      */
1980     keystr = hostkey->fmtkey();
1981     verify_ssh_host_key(savedhost, keystr);
1982     free(keystr);
1983
1984     /*
1985      * Send SSH2_MSG_NEWKEYS.
1986      */
1987     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1988     ssh2_pkt_send();
1989
1990     /*
1991      * Create and initialise session keys.
1992      */
1993     cscipher = cscipher_tobe;
1994     sccipher = sccipher_tobe;
1995     csmac = csmac_tobe;
1996     scmac = scmac_tobe;
1997     cscomp = cscomp_tobe;
1998     sccomp = sccomp_tobe;
1999     /*
2000      * Set IVs after keys.
2001      */
2002     ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2003     ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
2004     ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2005     ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2006     ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2007     ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2008
2009     /*
2010      * Now we're encrypting. Begin returning 1 to the protocol main
2011      * function so that other things can run on top of the
2012      * transport. If we ever see a KEXINIT, we must go back to the
2013      * start.
2014      */
2015     do {
2016         crReturn(1);
2017     } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2018     goto begin_key_exchange;
2019
2020     crFinish(1);
2021 }
2022
2023 /*
2024  * Handle the SSH2 userauth and connection layers.
2025  */
2026 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2027 {
2028     static unsigned long remote_winsize;
2029     static unsigned long remote_maxpkt;
2030
2031     crBegin;
2032
2033     /*
2034      * Request userauth protocol, and await a response to it.
2035      */
2036     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2037     ssh2_pkt_addstring("ssh-userauth");
2038     ssh2_pkt_send();
2039     crWaitUntilV(ispkt);
2040     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2041         fatalbox("Server refused user authentication protocol");
2042
2043     /*
2044      * FIXME: currently we support only password authentication.
2045      * (This places us technically in violation of the SSH2 spec.
2046      * We must fix this.)
2047      */
2048     while (1) {
2049         /*
2050          * Get a username and a password.
2051          */
2052         static char username[100];
2053         static char password[100];
2054         static int pos = 0;
2055         static char c;
2056
2057         if ((flags & FLAG_CONNECTION) && !*cfg.username) {
2058             c_write("login as: ", 10);
2059             while (pos >= 0) {
2060                 crWaitUntilV(!ispkt);
2061                 while (inlen--) switch (c = *in++) {
2062                   case 10: case 13:
2063                     username[pos] = 0;
2064                     pos = -1;
2065                     break;
2066                   case 8: case 127:
2067                     if (pos > 0) {
2068                         c_write("\b \b", 3);
2069                         pos--;
2070                     }
2071                     break;
2072                   case 21: case 27:
2073                     while (pos > 0) {
2074                         c_write("\b \b", 3);
2075                         pos--;
2076                     }
2077                     break;
2078                   case 3: case 4:
2079                     random_save_seed();
2080                     exit(0);
2081                     break;
2082                   default:
2083                     if (((c >= ' ' && c <= '~') ||
2084                          ((unsigned char)c >= 160)) && pos < 40) {
2085                         username[pos++] = c;
2086                         c_write(&c, 1);
2087                     }
2088                     break;
2089                 }
2090             }
2091             c_write("\r\n", 2);
2092             username[strcspn(username, "\n\r")] = '\0';
2093         } else {
2094             char stuff[200];
2095             strncpy(username, cfg.username, 99);
2096             username[99] = '\0';
2097             if (flags & FLAG_VERBOSE) {
2098                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2099                 c_write(stuff, strlen(stuff));
2100             }
2101         }
2102
2103         if (!(flags & FLAG_WINDOWED)) {
2104             char prompt[200];
2105             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2106             if (!ssh_get_password(prompt, password, sizeof(password))) {
2107                 /*
2108                  * get_password failed to get a password (for
2109                  * example because one was supplied on the command
2110                  * line which has already failed to work).
2111                  * Terminate.
2112                  */
2113                 logevent("No more passwords to try");
2114                 ssh_state = SSH_STATE_CLOSED;
2115                 crReturnV;
2116             }
2117         } else {
2118             c_write("password: ", 10);
2119
2120             pos = 0;
2121             while (pos >= 0) {
2122                 crWaitUntilV(!ispkt);
2123                 while (inlen--) switch (c = *in++) {
2124                   case 10: case 13:
2125                     password[pos] = 0;
2126                     pos = -1;
2127                     break;
2128                   case 8: case 127:
2129                     if (pos > 0)
2130                         pos--;
2131                     break;
2132                   case 21: case 27:
2133                     pos = 0;
2134                     break;
2135                   case 3: case 4:
2136                     random_save_seed();
2137                     exit(0);
2138                     break;
2139                   default:
2140                     if (((c >= ' ' && c <= '~') ||
2141                          ((unsigned char)c >= 160)) && pos < 40)
2142                         password[pos++] = c;
2143                     break;
2144                 }
2145             }
2146             c_write("\r\n", 2);
2147         }
2148
2149         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2150         ssh2_pkt_addstring(username);
2151         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2152         ssh2_pkt_addstring("password");
2153         ssh2_pkt_addbool(FALSE);
2154         ssh2_pkt_addstring(password);
2155         ssh2_pkt_send();
2156
2157         crWaitUntilV(ispkt);
2158         if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2159             c_write("Access denied\r\n", 15);
2160             logevent("Authentication refused");
2161         } else
2162             break;
2163     }
2164
2165     /*
2166      * Now we're authenticated for the connection protocol. The
2167      * connection protocol will automatically have started at this
2168      * point; there's no need to send SERVICE_REQUEST.
2169      */
2170
2171     /*
2172      * So now create a channel with a session in it.
2173      */
2174     mainchan = malloc(sizeof(struct ssh_channel));
2175     mainchan->localid = 100;           /* as good as any */
2176     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2177     ssh2_pkt_addstring("session");
2178     ssh2_pkt_adduint32(mainchan->localid);
2179     ssh2_pkt_adduint32(0x7FFFFFFFUL);  /* our window size */
2180     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
2181     ssh2_pkt_send();
2182     crWaitUntilV(ispkt);
2183     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2184         fatalbox("Server refused to open a session");
2185         /* FIXME: error data comes back in FAILURE packet */
2186     }
2187     if (ssh2_pkt_getuint32() != mainchan->localid) {
2188         fatalbox("Server's channel confirmation cited wrong channel");
2189     }
2190     mainchan->remoteid = ssh2_pkt_getuint32();
2191     mainchan->u.v2.remwindow = ssh2_pkt_getuint32();
2192     mainchan->u.v2.remmaxpkt = ssh2_pkt_getuint32();
2193     mainchan->u.v2.outbuffer = NULL;
2194     mainchan->u.v2.outbuflen = mainchan->u.v2.outbufsize = 0;
2195     logevent("Opened channel for session");
2196
2197     /*
2198      * Now allocate a pty for the session.
2199      */
2200     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2201     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2202     ssh2_pkt_addstring("pty-req");
2203     ssh2_pkt_addbool(1);               /* want reply */
2204     ssh2_pkt_addstring(cfg.termtype);
2205     ssh2_pkt_adduint32(cols);
2206     ssh2_pkt_adduint32(rows);
2207     ssh2_pkt_adduint32(0);             /* pixel width */
2208     ssh2_pkt_adduint32(0);             /* pixel height */
2209     ssh2_pkt_addstring_start();
2210     ssh2_pkt_addstring_data("\0", 1);  /* TTY_OP_END, no special options */
2211     ssh2_pkt_send();
2212
2213     do {                               /* FIXME: pay attention to these */
2214         crWaitUntilV(ispkt);
2215     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2216
2217     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2218         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2219             fatalbox("Server got confused by pty request");
2220         }
2221         c_write("Server refused to allocate pty\r\n", 32);
2222     } else {
2223         logevent("Allocated pty");
2224     }
2225
2226     /*
2227      * Start a shell.
2228      */
2229     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2230     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2231     ssh2_pkt_addstring("shell");
2232     ssh2_pkt_addbool(1);               /* want reply */
2233     ssh2_pkt_send();
2234     do {
2235         crWaitUntilV(ispkt);
2236         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2237             /* FIXME: be able to handle other channels here */
2238             if (ssh2_pkt_getuint32() != mainchan->localid)
2239                 continue;          /* wrong channel */
2240             mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2241         }
2242     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2243     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2244         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2245             fatalbox("Server got confused by shell request");
2246         }
2247         fatalbox("Server refused to start a shell");
2248     } else {
2249         logevent("Started a shell");
2250     }
2251
2252     /*
2253      * Transfer data!
2254      */
2255     ssh_send_ok = 1;
2256     while (1) {
2257         static int try_send;
2258         crReturnV;
2259         try_send = FALSE;
2260         if (ispkt) {
2261             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2262                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2263                 char *data;
2264                 int length;
2265                 /* FIXME: be able to handle other channels here */
2266                 if (ssh2_pkt_getuint32() != mainchan->localid)
2267                     continue;          /* wrong channel */
2268                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2269                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2270                     continue;          /* extended but not stderr */
2271                 ssh2_pkt_getstring(&data, &length);
2272                 if (data) {
2273                     c_write(data, length);
2274                     /*
2275                      * Enlarge the window again at the remote side,
2276                      * just in case it ever runs down and they fail
2277                      * to send us any more data.
2278                      */
2279                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2280                     ssh2_pkt_adduint32(mainchan->remoteid);
2281                     ssh2_pkt_adduint32(length);
2282                     ssh2_pkt_send();
2283                 }
2284             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2285                 ssh_state = SSH_STATE_CLOSED;
2286                 logevent("Received disconnect message");
2287             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2288                 continue;              /* exit status et al; ignore (FIXME?) */
2289             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2290                 continue;              /* remote sends EOF; ignore */
2291             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2292                 /* FIXME: be able to handle other channels here */
2293                 if (ssh2_pkt_getuint32() != mainchan->localid)
2294                     continue;          /* wrong channel */
2295                 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2296                 ssh2_pkt_adduint32(mainchan->remoteid);
2297                 ssh2_pkt_send();
2298                 /* FIXME: mark the channel as closed */
2299                 if (1 /* FIXME: "all channels are closed" */) {
2300                     logevent("All channels closed. Disconnecting");
2301                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2302                     ssh2_pkt_send();
2303                 }
2304                 continue;              /* remote sends close; ignore (FIXME) */
2305             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2306                 /* FIXME: be able to handle other channels here */
2307                 if (ssh2_pkt_getuint32() != mainchan->localid)
2308                     continue;          /* wrong channel */
2309                 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2310                 try_send = TRUE;
2311             } else {
2312                 fatalbox("Strange packet received: type %d", pktin.type);
2313             }
2314         } else {
2315             /*
2316              * We have spare data. Add it to the channel buffer.
2317              */
2318             if (mainchan->u.v2.outbufsize <
2319                 mainchan->u.v2.outbuflen + inlen) {
2320                 mainchan->u.v2.outbufsize =
2321                     mainchan->u.v2.outbuflen + inlen + 1024;
2322                 mainchan->u.v2.outbuffer = srealloc(mainchan->u.v2.outbuffer,
2323                                                     mainchan->u.v2.outbufsize);
2324             }
2325             memcpy(mainchan->u.v2.outbuffer + mainchan->u.v2.outbuflen,
2326                    in, inlen);
2327             mainchan->u.v2.outbuflen += inlen;
2328             try_send = TRUE;
2329         }
2330         if (try_send) {
2331             /*
2332              * Try to send data on the channel if we can. (FIXME:
2333              * on _all_ channels.)
2334              */
2335             while (mainchan->u.v2.remwindow > 0 &&
2336                    mainchan->u.v2.outbuflen > 0) {
2337                 unsigned len = mainchan->u.v2.remwindow;
2338                 if (len > mainchan->u.v2.outbuflen)
2339                     len = mainchan->u.v2.outbuflen;
2340                 if (len > mainchan->u.v2.remmaxpkt)
2341                     len = mainchan->u.v2.remmaxpkt;
2342                 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2343                 ssh2_pkt_adduint32(mainchan->remoteid);
2344                 ssh2_pkt_addstring_start();
2345                 ssh2_pkt_addstring_data(mainchan->u.v2.outbuffer, len);
2346                 ssh2_pkt_send();
2347                 mainchan->u.v2.outbuflen -= len;
2348                 memmove(mainchan->u.v2.outbuffer, mainchan->u.v2.outbuffer+len,
2349                         mainchan->u.v2.outbuflen);
2350                 mainchan->u.v2.remwindow -= len;
2351             }
2352         }
2353     }
2354
2355     crFinishV;
2356 }
2357
2358 /*
2359  * Handle the top-level SSH2 protocol.
2360  */
2361 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2362 {
2363     if (do_ssh2_transport(in, inlen, ispkt) == 0)
2364         return;
2365     do_ssh2_authconn(in, inlen, ispkt);
2366 }
2367
2368 /*
2369  * Called to set up the connection. Will arrange for WM_NETEVENT
2370  * messages to be passed to the specified window, whose window
2371  * procedure should then call telnet_msg().
2372  *
2373  * Returns an error message, or NULL on success.
2374  */
2375 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2376     char *p;
2377         
2378 #ifdef MSCRYPTOAPI
2379     if(crypto_startup() == 0)
2380         return "Microsoft high encryption pack not installed!";
2381 #endif
2382
2383     p = connect_to_host(host, port, realhost);
2384     if (p != NULL)
2385         return p;
2386
2387     if (!do_ssh_init())
2388         return "Protocol initialisation error";
2389
2390     if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2391         switch (WSAGetLastError()) {
2392           case WSAENETDOWN: return "Network is down";
2393           default: return "WSAAsyncSelect(): unknown error";
2394         }
2395
2396     return NULL;
2397 }
2398
2399 /*
2400  * Process a WM_NETEVENT message. Will return 0 if the connection
2401  * has closed, or <0 for a socket error.
2402  */
2403 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2404     int ret;
2405     char buf[256];
2406
2407     /*
2408      * Because reading less than the whole of the available pending
2409      * data can generate an FD_READ event, we need to allow for the
2410      * possibility that FD_READ may arrive with FD_CLOSE already in
2411      * the queue; so it's possible that we can get here even with s
2412      * invalid. If so, we return 1 and don't worry about it.
2413      */
2414     if (s == INVALID_SOCKET)
2415         return 1;
2416
2417     if (WSAGETSELECTERROR(lParam) != 0)
2418         return -WSAGETSELECTERROR(lParam);
2419
2420     switch (WSAGETSELECTEVENT(lParam)) {
2421       case FD_READ:
2422       case FD_CLOSE:
2423         ret = recv(s, buf, sizeof(buf), 0);
2424         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2425             return 1;
2426         if (ret < 0)                   /* any _other_ error */
2427             return -10000-WSAGetLastError();
2428         if (ret == 0) {
2429             s = INVALID_SOCKET;
2430             return 0;
2431         }
2432         ssh_gotdata (buf, ret);
2433         if (ssh_state == SSH_STATE_CLOSED) {
2434             closesocket(s);
2435             s = INVALID_SOCKET;
2436             return 0;
2437         }
2438         return 1;
2439     }
2440     return 1;                          /* shouldn't happen, but WTF */
2441 }
2442
2443 /*
2444  * Called to send data down the Telnet connection.
2445  */
2446 static void ssh_send (char *buf, int len) {
2447     if (s == INVALID_SOCKET)
2448         return;
2449
2450     ssh_protocol(buf, len, 0);
2451 }
2452
2453 /*
2454  * Called to set the size of the window from Telnet's POV.
2455  */
2456 static void ssh_size(void) {
2457     switch (ssh_state) {
2458       case SSH_STATE_BEFORE_SIZE:
2459       case SSH_STATE_CLOSED:
2460         break;                         /* do nothing */
2461       case SSH_STATE_INTERMED:
2462         size_needed = TRUE;            /* buffer for later */
2463         break;
2464       case SSH_STATE_SESSION:
2465         if (!cfg.nopty) {
2466             send_packet(SSH1_CMSG_WINDOW_SIZE,
2467                         PKT_INT, rows, PKT_INT, cols,
2468                         PKT_INT, 0, PKT_INT, 0, PKT_END);
2469         }
2470     }
2471 }
2472
2473 /*
2474  * Send Telnet special codes. TS_EOF is useful for `plink', so you
2475  * can send an EOF and collect resulting output (e.g. `plink
2476  * hostname sort').
2477  */
2478 static void ssh_special (Telnet_Special code) {
2479     if (code == TS_EOF) {
2480         if (ssh_version = 1) {
2481             send_packet(SSH1_CMSG_EOF, PKT_END);
2482         } else {
2483             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2484             ssh2_pkt_adduint32(mainchan->remoteid);
2485             ssh2_pkt_send();
2486         }
2487     } else {
2488         /* do nothing */
2489     }
2490 }
2491
2492
2493 /*
2494  * Read and decrypt one incoming SSH packet.
2495  * (only used by pSCP)
2496  */
2497 static void get_packet(void)
2498 {
2499     unsigned char buf[4096], *p;
2500     long to_read;
2501     int len;
2502
2503     p = NULL;
2504     len = 0;
2505
2506     while ((to_read = s_rdpkt(&p, &len)) > 0) {
2507         if (to_read > sizeof(buf)) to_read = sizeof(buf);
2508         len = s_read(buf, to_read);
2509         if (len != to_read) {
2510             closesocket(s);
2511             s = INVALID_SOCKET;
2512             return;
2513         }
2514         p = buf;
2515     }
2516
2517     assert(len == 0);
2518 }
2519
2520 /*
2521  * Receive a block of data over the SSH link. Block until
2522  * all data is available. Return nr of bytes read (0 if lost connection).
2523  * (only used by pSCP)
2524  */
2525 int ssh_scp_recv(unsigned char *buf, int len)
2526 {
2527     static int pending_input_len = 0;
2528     static unsigned char *pending_input_ptr;
2529     int to_read = len;
2530
2531     if (pending_input_len >= to_read) {
2532         memcpy(buf, pending_input_ptr, to_read);
2533         pending_input_ptr += to_read;
2534         pending_input_len -= to_read;
2535         return len;
2536     }
2537     
2538     if (pending_input_len > 0) {
2539         memcpy(buf, pending_input_ptr, pending_input_len);
2540         buf += pending_input_len;
2541         to_read -= pending_input_len;
2542         pending_input_len = 0;
2543     }
2544
2545     if (s == INVALID_SOCKET)
2546         return 0;
2547     while (to_read > 0) {
2548         get_packet();
2549         if (s == INVALID_SOCKET)
2550             return 0;
2551         if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2552             int plen = GET_32BIT(pktin.body);
2553             if (plen <= to_read) {
2554                 memcpy(buf, pktin.body + 4, plen);
2555                 buf += plen;
2556                 to_read -= plen;
2557             } else {
2558                 memcpy(buf, pktin.body + 4, to_read);
2559                 pending_input_len = plen - to_read;
2560                 pending_input_ptr = pktin.body + 4 + to_read;
2561                 to_read = 0;
2562             }
2563         } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2564             int plen = GET_32BIT(pktin.body);
2565             fwrite(pktin.body + 4, plen, 1, stderr);
2566         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2567                 logevent("Received disconnect request");
2568         } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2569                    pktin.type == SSH1_SMSG_FAILURE) {
2570                 /* ignore */
2571         } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2572             char logbuf[100];
2573             sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2574             logevent(logbuf);
2575             send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2576             logevent("Closing connection");
2577             closesocket(s);
2578             s = INVALID_SOCKET;
2579         } else {
2580             fatalbox("Strange packet received: type %d", pktin.type);
2581         }
2582     }
2583
2584     return len;
2585 }
2586
2587 /*
2588  * Send a block of data over the SSH link.
2589  * Block until all data is sent.
2590  * (only used by pSCP)
2591  */
2592 void ssh_scp_send(unsigned char *buf, int len)
2593 {
2594     if (s == INVALID_SOCKET)
2595         return;
2596     send_packet(SSH1_CMSG_STDIN_DATA,
2597                 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2598 }
2599
2600 /*
2601  * Send an EOF notification to the server.
2602  * (only used by pSCP)
2603  */
2604 void ssh_scp_send_eof(void)
2605 {
2606     if (s == INVALID_SOCKET)
2607         return;
2608     send_packet(SSH1_CMSG_EOF, PKT_END);
2609 }
2610
2611 /*
2612  * Set up the connection, login on the remote host and
2613  * start execution of a command.
2614  * Returns an error message, or NULL on success.
2615  * (only used by pSCP)
2616  */
2617 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2618 {
2619     char buf[160], *p;
2620
2621 #ifdef MSCRYPTOAPI
2622     if (crypto_startup() == 0)
2623         return "Microsoft high encryption pack not installed!";
2624 #endif
2625
2626     p = connect_to_host(host, port, realhost);
2627     if (p != NULL)
2628         return p;
2629
2630     random_init();
2631
2632     if (!do_ssh_init())
2633         return "Protocol initialisation error";
2634
2635     /* Exchange keys and login */
2636     do {
2637         get_packet();
2638         if (s == INVALID_SOCKET)
2639             return "Connection closed by remote host";
2640     } while (!do_ssh1_login(NULL, 0, 1));
2641
2642     if (ssh_state == SSH_STATE_CLOSED) {
2643         closesocket(s);
2644         s = INVALID_SOCKET;
2645         return "Session initialisation error";
2646     }
2647
2648     /* Execute command */
2649     sprintf(buf, "Sending command: %.100s", cmd);
2650     logevent(buf);
2651     send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2652
2653     return NULL;
2654 }
2655
2656 static SOCKET ssh_socket(void) { return s; }
2657
2658 static int ssh_sendok(void) { return ssh_send_ok; }
2659
2660 Backend ssh_backend = {
2661     ssh_init,
2662     ssh_msg,
2663     ssh_send,
2664     ssh_size,
2665     ssh_special,
2666     ssh_socket,
2667     ssh_sendok
2668 };