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