]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Make the SSH2 traffic analysis defence robust in the face of Zlib
[PuTTY.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, \
23                           (s ? sk_close(s), s = NULL : 0), \
24                           connection_fatal msg )
25
26 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
29 #define SSH1_CMSG_USER                            4    /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
38 #define SSH1_SMSG_SUCCESS                         14   /* 0xe */
39 #define SSH1_SMSG_FAILURE                         15   /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
43 #define SSH1_CMSG_EOF                             19   /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN                        27   /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST            28   /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN                        29   /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
55 #define SSH1_MSG_IGNORE                           32   /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING          34   /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA                 35   /* 0x23 */
59 #define SSH1_MSG_DEBUG                            36   /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION             37   /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
67
68 #define SSH1_AUTH_TIS                             5    /* 0x5 */
69 #define SSH1_AUTH_CCARD                           16   /* 0x10 */
70
71 #define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
72 #define SSH2_MSG_IGNORE                           2    /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
74 #define SSH2_MSG_DEBUG                            4    /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
77 #define SSH2_MSG_KEXINIT                          20   /* 0x14 */
78 #define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
81 #define SSH2_MSG_KEX_DH_GEX_REQUEST               30   /* 0x1e */
82 #define SSH2_MSG_KEX_DH_GEX_GROUP                 31   /* 0x1f */
83 #define SSH2_MSG_KEX_DH_GEX_INIT                  32   /* 0x20 */
84 #define SSH2_MSG_KEX_DH_GEX_REPLY                 33   /* 0x21 */
85 #define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
86 #define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
87 #define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
88 #define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
89 #define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
90 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
91 #define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
92 #define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
93 #define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
94 #define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
95 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
96 #define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
97 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
98 #define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
99 #define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
100 #define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
101 #define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
102 #define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
103 #define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
104 #define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
105
106 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1  /* 0x1 */
107 #define SSH2_DISCONNECT_PROTOCOL_ERROR            2    /* 0x2 */
108 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED       3    /* 0x3 */
109 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4   /* 0x4 */
110 #define SSH2_DISCONNECT_MAC_ERROR                 5    /* 0x5 */
111 #define SSH2_DISCONNECT_COMPRESSION_ERROR         6    /* 0x6 */
112 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE     7    /* 0x7 */
113 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE   9    /* 0x9 */
115 #define SSH2_DISCONNECT_CONNECTION_LOST           10   /* 0xa */
116 #define SSH2_DISCONNECT_BY_APPLICATION            11   /* 0xb */
117
118 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
119 #define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
120 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
121 #define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
122
123 #define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
124
125 #define GET_32BIT(cp) \
126     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
127     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
128     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
129     ((unsigned long)(unsigned char)(cp)[3]))
130
131 #define PUT_32BIT(cp, value) { \
132     (cp)[0] = (unsigned char)((value) >> 24); \
133     (cp)[1] = (unsigned char)((value) >> 16); \
134     (cp)[2] = (unsigned char)((value) >> 8); \
135     (cp)[3] = (unsigned char)(value); }
136
137 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
138
139 /* Coroutine mechanics for the sillier bits of the code */
140 #define crBegin1        static int crLine = 0;
141 #define crBegin2        switch(crLine) { case 0:;
142 #define crBegin         crBegin1; crBegin2;
143 #define crFinish(z)     } crLine = 0; return (z)
144 #define crFinishV       } crLine = 0; return
145 #define crReturn(z)     \
146         do {\
147             crLine=__LINE__; return (z); case __LINE__:;\
148         } while (0)
149 #define crReturnV       \
150         do {\
151             crLine=__LINE__; return; case __LINE__:;\
152         } while (0)
153 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
154 #define crStopV         do{ crLine = 0; return; }while(0)
155 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
156 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
157
158 extern char *x11_init (Socket *, char *, void *);
159 extern void x11_close (Socket);
160 extern void x11_send  (Socket , char *, int);
161 extern void x11_invent_auth(char *, int, char *, int);
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 ssh2_ciphers *ciphers[] = {
170     &ssh2_aes,
171     &ssh2_blowfish,
172     &ssh2_3des,
173 };
174
175 const static struct ssh_kex *kex_algs[] = {
176 #ifdef DO_DIFFIE_HELLMAN_GEX
177     &ssh_diffiehellman_gex,
178 #endif
179     &ssh_diffiehellman };
180
181 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
182
183 static void nullmac_key(unsigned char *key) { }
184 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
185 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
186 const static struct ssh_mac ssh_mac_none = {
187     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
188 };
189 const static struct ssh_mac *macs[] = {
190     &ssh_sha1, &ssh_md5, &ssh_mac_none };
191 const static struct ssh_mac *buggymacs[] = {
192     &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
193
194 static void ssh_comp_none_init(void) { }
195 static int ssh_comp_none_block(unsigned char *block, int len,
196                                unsigned char **outblock, int *outlen) {
197     return 0;
198 }
199 const static struct ssh_compress ssh_comp_none = {
200     "none",
201     ssh_comp_none_init, ssh_comp_none_block,
202     ssh_comp_none_init, ssh_comp_none_block
203 };
204 extern const struct ssh_compress ssh_zlib;
205 const static struct ssh_compress *compressions[] = {
206     &ssh_zlib, &ssh_comp_none };
207
208 enum {                                 /* channel types */
209     CHAN_MAINSESSION,
210     CHAN_X11,
211     CHAN_AGENT,
212 };
213
214 /*
215  * 2-3-4 tree storing channels.
216  */
217 struct ssh_channel {
218     unsigned remoteid, localid;
219     int type;
220     int closes;
221     struct ssh2_data_channel {
222         unsigned char *outbuffer;
223         unsigned outbuflen, outbufsize;
224         unsigned remwindow, remmaxpkt;
225     } v2;
226     union {
227         struct ssh_agent_channel {
228             unsigned char *message;
229             unsigned char msglen[4];
230             int lensofar, totallen;
231         } a;
232         struct ssh_x11_channel {
233             Socket s;
234         } x11;
235     } u;
236 };
237
238 struct Packet {
239     long length;
240     int type;
241     unsigned char *data;
242     unsigned char *body;
243     long savedpos;
244     long maxlen;
245 };
246
247 static SHA_State exhash, exhashbase;
248
249 static Socket s = NULL;
250
251 static unsigned char session_key[32];
252 static int ssh1_compressing;
253 static int ssh_agentfwd_enabled;
254 static int ssh_X11_fwd_enabled;
255 static const struct ssh_cipher *cipher = NULL;
256 static const struct ssh2_cipher *cscipher = NULL;
257 static const struct ssh2_cipher *sccipher = NULL;
258 static const struct ssh_mac *csmac = NULL;
259 static const struct ssh_mac *scmac = NULL;
260 static const struct ssh_compress *cscomp = NULL;
261 static const struct ssh_compress *sccomp = NULL;
262 static const struct ssh_kex *kex = NULL;
263 static const struct ssh_signkey *hostkey = NULL;
264 static unsigned char ssh2_session_id[20];
265 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
266
267 static char *savedhost;
268 static int savedport;
269 static int ssh_send_ok;
270 static int ssh_echoing, ssh_editing;
271
272 static tree234 *ssh_channels;           /* indexed by local id */
273 static struct ssh_channel *mainchan;   /* primary session channel */
274
275 static enum {
276     SSH_STATE_PREPACKET,
277     SSH_STATE_BEFORE_SIZE,
278     SSH_STATE_INTERMED,
279     SSH_STATE_SESSION,
280     SSH_STATE_CLOSED
281 } ssh_state = SSH_STATE_PREPACKET;
282
283 static int size_needed = FALSE, eof_needed = FALSE;
284
285 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
286 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
287 static unsigned char *deferred_send_data = NULL;
288 static int deferred_len = 0, deferred_size = 0;
289
290 static int ssh_version;
291 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
292 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
293 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
294 static void ssh_size(void);
295 static void ssh_special (Telnet_Special);
296 static void ssh2_try_send(struct ssh_channel *c);
297 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
298
299 static int (*s_rdpkt)(unsigned char **data, int *datalen);
300
301 static struct rdpkt1_state_tag {
302     long len, pad, biglen, to_read;
303     unsigned long realcrc, gotcrc;
304     unsigned char *p;
305     int i;
306     int chunk;
307 } rdpkt1_state;
308
309 static struct rdpkt2_state_tag {
310     long len, pad, payload, packetlen, maclen;
311     int i;
312     int cipherblk;
313     unsigned long incoming_sequence;
314 } rdpkt2_state;
315
316 static int ssh_channelcmp(void *av, void *bv) {
317     struct ssh_channel *a = (struct ssh_channel *)av;
318     struct ssh_channel *b = (struct ssh_channel *)bv;
319     if (a->localid < b->localid) return -1;
320     if (a->localid > b->localid) return +1;
321     return 0;
322 }
323 static int ssh_channelfind(void *av, void *bv) {
324     unsigned *a = (unsigned *)av;
325     struct ssh_channel *b = (struct ssh_channel *)bv;
326     if (*a < b->localid) return -1;
327     if (*a > b->localid) return +1;
328     return 0;
329 }
330
331 static void c_write (char *buf, int len) {
332     if ((flags & FLAG_STDERR)) {
333         int i;
334         for (i = 0; i < len; i++)
335             if (buf[i] != '\r')
336                 fputc(buf[i], stderr);
337         return;
338     }
339     from_backend(1, buf, len);
340 }
341
342 static void c_write_str (char *buf) {
343     c_write(buf, strlen(buf));
344 }
345
346 /*
347  * Collect incoming data in the incoming packet buffer.
348  * Decipher and verify the packet when it is completely read.
349  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
350  * Update the *data and *datalen variables.
351  * Return the additional nr of bytes needed, or 0 when
352  * a complete packet is available.
353  */
354 static int ssh1_rdpkt(unsigned char **data, int *datalen)
355 {
356     struct rdpkt1_state_tag *st = &rdpkt1_state;
357
358     crBegin;
359
360 next_packet:
361
362     pktin.type = 0;
363     pktin.length = 0;
364
365     for (st->i = st->len = 0; st->i < 4; st->i++) {
366         while ((*datalen) == 0)
367             crReturn(4-st->i);
368         st->len = (st->len << 8) + **data;
369         (*data)++, (*datalen)--;
370     }
371
372 #ifdef FWHACK
373     if (st->len == 0x52656d6f) {        /* "Remo"te server has closed ... */
374         st->len = 0x300;                /* big enough to carry to end */
375     }
376 #endif
377
378     st->pad = 8 - (st->len % 8);
379     st->biglen = st->len + st->pad;
380     pktin.length = st->len - 5;
381
382     if (pktin.maxlen < st->biglen) {
383         pktin.maxlen = st->biglen;
384         pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
385                       srealloc(pktin.data, st->biglen+APIEXTRA));
386         if (!pktin.data)
387             fatalbox("Out of memory");
388     }
389
390     st->to_read = st->biglen;
391     st->p = pktin.data;
392     while (st->to_read > 0) {
393         st->chunk = st->to_read;
394         while ((*datalen) == 0)
395             crReturn(st->to_read);
396         if (st->chunk > (*datalen))
397             st->chunk = (*datalen);
398         memcpy(st->p, *data, st->chunk);
399         *data += st->chunk;
400         *datalen -= st->chunk;
401         st->p += st->chunk;
402         st->to_read -= st->chunk;
403     }
404
405     if (cipher)
406         cipher->decrypt(pktin.data, st->biglen);
407 #if 0
408     debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
409     for (st->i = 0; st->i < st->biglen; st->i++)
410         debug(("  %02x", (unsigned char)pktin.data[st->i]));
411     debug(("\r\n"));
412 #endif
413
414     st->realcrc = crc32(pktin.data, st->biglen-4);
415     st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
416     if (st->gotcrc != st->realcrc) {
417         bombout(("Incorrect CRC received on packet"));
418         crReturn(0);
419     }
420
421     pktin.body = pktin.data + st->pad + 1;
422
423     if (ssh1_compressing) {
424         unsigned char *decompblk;
425         int decomplen;
426 #if 0
427         int i;
428         debug(("Packet payload pre-decompression:\n"));
429         for (i = -1; i < pktin.length; i++)
430             debug(("  %02x", (unsigned char)pktin.body[i]));
431         debug(("\r\n"));
432 #endif
433         zlib_decompress_block(pktin.body-1, pktin.length+1,
434                               &decompblk, &decomplen);
435
436         if (pktin.maxlen < st->pad + decomplen) {
437             pktin.maxlen = st->pad + decomplen;
438             pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
439             pktin.body = pktin.data + st->pad + 1;
440             if (!pktin.data)
441                 fatalbox("Out of memory");
442         }
443
444         memcpy(pktin.body-1, decompblk, decomplen);
445         sfree(decompblk);
446         pktin.length = decomplen-1;
447 #if 0
448         debug(("Packet payload post-decompression:\n"));
449         for (i = -1; i < pktin.length; i++)
450             debug(("  %02x", (unsigned char)pktin.body[i]));
451         debug(("\r\n"));
452 #endif
453     }
454
455     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
456         pktin.type == SSH1_SMSG_STDERR_DATA ||
457         pktin.type == SSH1_MSG_DEBUG ||
458         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
459         pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
460         long strlen = GET_32BIT(pktin.body);
461         if (strlen + 4 != pktin.length) {
462             bombout(("Received data packet with bogus string length"));
463             crReturn(0);
464         }
465     }
466
467     pktin.type = pktin.body[-1];
468
469     if (pktin.type == SSH1_MSG_DEBUG) {
470         /* log debug message */
471         char buf[80];
472         int strlen = GET_32BIT(pktin.body);
473         strcpy(buf, "Remote: ");
474         if (strlen > 70) strlen = 70;
475         memcpy(buf+8, pktin.body+4, strlen);
476         buf[8+strlen] = '\0';
477         logevent(buf);
478         goto next_packet;
479     } else if (pktin.type == SSH1_MSG_IGNORE) {
480         /* do nothing */
481         goto next_packet;
482     }
483
484     crFinish(0);
485 }
486
487 static int ssh2_rdpkt(unsigned char **data, int *datalen)
488 {
489     struct rdpkt2_state_tag *st = &rdpkt2_state;
490
491     crBegin;
492
493 next_packet:
494     pktin.type = 0;
495     pktin.length = 0;
496     if (sccipher)
497         st->cipherblk = sccipher->blksize;
498     else
499         st->cipherblk = 8;
500     if (st->cipherblk < 8)
501         st->cipherblk = 8;
502
503     if (pktin.maxlen < st->cipherblk) {
504         pktin.maxlen = st->cipherblk;
505         pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
506                       srealloc(pktin.data, st->cipherblk+APIEXTRA));
507         if (!pktin.data)
508             fatalbox("Out of memory");
509     }
510
511     /*
512      * Acquire and decrypt the first block of the packet. This will
513      * contain the length and padding details.
514      */
515      for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
516         while ((*datalen) == 0)
517             crReturn(st->cipherblk-st->i);
518         pktin.data[st->i] = *(*data)++;
519         (*datalen)--;
520     }
521 #ifdef FWHACK
522     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
523         /* FIXME */
524     }
525 #endif
526     if (sccipher)
527         sccipher->decrypt(pktin.data, st->cipherblk);
528
529     /*
530      * Now get the length and padding figures.
531      */
532     st->len = GET_32BIT(pktin.data);
533     st->pad = pktin.data[4];
534
535     /*
536      * This enables us to deduce the payload length.
537      */
538     st->payload = st->len - st->pad - 1;
539
540     pktin.length = st->payload + 5;
541
542     /*
543      * So now we can work out the total packet length.
544      */
545     st->packetlen = st->len + 4;
546     st->maclen = scmac ? scmac->len : 0;
547
548     /*
549      * Adjust memory allocation if packet is too big.
550      */
551     if (pktin.maxlen < st->packetlen+st->maclen) {
552         pktin.maxlen = st->packetlen+st->maclen;
553         pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
554                       srealloc(pktin.data, pktin.maxlen+APIEXTRA));
555         if (!pktin.data)
556             fatalbox("Out of memory");
557     }
558
559     /*
560      * Read and decrypt the remainder of the packet.
561      */
562     for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
563         while ((*datalen) == 0)
564             crReturn(st->packetlen + st->maclen - st->i);
565         pktin.data[st->i] = *(*data)++;
566         (*datalen)--;
567     }
568     /* Decrypt everything _except_ the MAC. */
569     if (sccipher)
570         sccipher->decrypt(pktin.data + st->cipherblk,
571                           st->packetlen - st->cipherblk);
572
573 #if 0
574     debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
575     for (st->i = 0; st->i < st->packetlen; st->i++)
576         debug(("  %02x", (unsigned char)pktin.data[st->i]));
577     debug(("\r\n"));
578 #endif
579
580     /*
581      * Check the MAC.
582      */
583     if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
584         bombout(("Incorrect MAC received on packet"));
585         crReturn(0);
586     }
587     st->incoming_sequence++;               /* whether or not we MACed */
588
589     /*
590      * Decompress packet payload.
591      */
592     {
593         unsigned char *newpayload;
594         int newlen;
595         if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
596                                          &newpayload, &newlen)) {
597             if (pktin.maxlen < newlen+5) {
598                 pktin.maxlen = newlen+5;
599                 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
600                               srealloc(pktin.data, pktin.maxlen+APIEXTRA));
601                 if (!pktin.data)
602                     fatalbox("Out of memory");
603             }
604             pktin.length = 5 + newlen;
605             memcpy(pktin.data+5, newpayload, newlen);
606 #if 0
607             debug(("Post-decompression payload:\r\n"));
608             for (st->i = 0; st->i < newlen; st->i++)
609                 debug(("  %02x", (unsigned char)pktin.data[5+st->i]));
610             debug(("\r\n"));
611 #endif
612
613             sfree(newpayload);
614         }
615     }
616
617     pktin.savedpos = 6;
618     pktin.type = pktin.data[5];
619
620     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
621         goto next_packet;              /* FIXME: print DEBUG message */
622
623     crFinish(0);
624 }
625
626 static void ssh1_pktout_size(int len) {
627     int pad, biglen;
628
629     len += 5;                          /* type and CRC */
630     pad = 8 - (len%8);
631     biglen = len + pad;
632
633     pktout.length = len-5;
634     if (pktout.maxlen < biglen) {
635         pktout.maxlen = biglen;
636 #ifdef MSCRYPTOAPI
637         /* Allocate enough buffer space for extra block
638          * for MS CryptEncrypt() */
639         pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
640                        srealloc(pktout.data, biglen+12));
641 #else
642         pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
643                        srealloc(pktout.data, biglen+4));
644 #endif
645         if (!pktout.data)
646             fatalbox("Out of memory");
647     }
648     pktout.body = pktout.data+4+pad+1;
649 }
650
651 static void s_wrpkt_start(int type, int len) {
652     ssh1_pktout_size(len);
653     pktout.type = type;
654 }
655
656 static int s_wrpkt_prepare(void) {
657     int pad, len, biglen, i;
658     unsigned long crc;
659
660     pktout.body[-1] = pktout.type;
661
662     if (ssh1_compressing) {
663         unsigned char *compblk;
664         int complen;
665 #if 0
666         debug(("Packet payload pre-compression:\n"));
667         for (i = -1; i < pktout.length; i++)
668             debug(("  %02x", (unsigned char)pktout.body[i]));
669         debug(("\r\n"));
670 #endif
671         zlib_compress_block(pktout.body-1, pktout.length+1,
672                             &compblk, &complen);
673         ssh1_pktout_size(complen-1);
674         memcpy(pktout.body-1, compblk, complen);
675         sfree(compblk);
676 #if 0
677         debug(("Packet payload post-compression:\n"));
678         for (i = -1; i < pktout.length; i++)
679             debug(("  %02x", (unsigned char)pktout.body[i]));
680         debug(("\r\n"));
681 #endif
682     }
683
684     len = pktout.length + 5;           /* type and CRC */
685     pad = 8 - (len%8);
686     biglen = len + pad;
687
688     for (i=0; i<pad; i++)
689         pktout.data[i+4] = random_byte();
690     crc = crc32(pktout.data+4, biglen-4);
691     PUT_32BIT(pktout.data+biglen, crc);
692     PUT_32BIT(pktout.data, len);
693
694 #if 0
695     debug(("Sending packet len=%d\r\n", biglen+4));
696     for (i = 0; i < biglen+4; i++)
697         debug(("  %02x", (unsigned char)pktout.data[i]));
698     debug(("\r\n"));
699 #endif
700     if (cipher)
701         cipher->encrypt(pktout.data+4, biglen);
702
703     return biglen+4;
704 }
705
706 static void s_wrpkt(void) {
707     int len;
708     len = s_wrpkt_prepare();
709     sk_write(s, pktout.data, len);
710 }
711
712 static void s_wrpkt_defer(void) {
713     int len;
714     len = s_wrpkt_prepare();
715     if (deferred_len + len > deferred_size) {
716         deferred_size = deferred_len + len + 128;
717         deferred_send_data = srealloc(deferred_send_data, deferred_size);
718     }
719     memcpy(deferred_send_data+deferred_len, pktout.data, len);
720     deferred_len += len;
721 }
722
723 /*
724  * Construct a packet with the specified contents.
725  */
726 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
727 {
728     unsigned char *p, *argp, argchar;
729     unsigned long argint;
730     int pktlen, argtype, arglen;
731     Bignum bn;
732
733     pktlen = 0;
734     while ((argtype = va_arg(ap1, int)) != PKT_END) {
735         switch (argtype) {
736           case PKT_INT:
737             (void) va_arg(ap1, int);
738             pktlen += 4;
739             break;
740           case PKT_CHAR:
741             (void) va_arg(ap1, char);
742             pktlen++;
743             break;
744           case PKT_DATA:
745             (void) va_arg(ap1, unsigned char *);
746             arglen = va_arg(ap1, int);
747             pktlen += arglen;
748             break;
749           case PKT_STR:
750             argp = va_arg(ap1, unsigned char *);
751             arglen = strlen(argp);
752             pktlen += 4 + arglen;
753             break;
754           case PKT_BIGNUM:
755             bn = va_arg(ap1, Bignum);
756             pktlen += ssh1_bignum_length(bn);
757             break;
758           default:
759             assert(0);
760         }
761     }
762
763     s_wrpkt_start(pkttype, pktlen);
764     p = pktout.body;
765
766     while ((argtype = va_arg(ap2, int)) != PKT_END) {
767         switch (argtype) {
768           case PKT_INT:
769             argint = va_arg(ap2, int);
770             PUT_32BIT(p, argint);
771             p += 4;
772             break;
773           case PKT_CHAR:
774             argchar = va_arg(ap2, unsigned char);
775             *p = argchar;
776             p++;
777             break;
778           case PKT_DATA:
779             argp = va_arg(ap2, unsigned char *);
780             arglen = va_arg(ap2, int);
781             memcpy(p, argp, arglen);
782             p += arglen;
783             break;
784           case PKT_STR:
785             argp = va_arg(ap2, unsigned char *);
786             arglen = strlen(argp);
787             PUT_32BIT(p, arglen);
788             memcpy(p + 4, argp, arglen);
789             p += 4 + arglen;
790             break;
791           case PKT_BIGNUM:
792             bn = va_arg(ap2, Bignum);
793             p += ssh1_write_bignum(p, bn);
794             break;
795         }
796     }
797 }
798
799 static void send_packet(int pkttype, ...) {
800     va_list ap1, ap2;
801     va_start(ap1, pkttype);
802     va_start(ap2, pkttype);
803     construct_packet(pkttype, ap1, ap2);
804     s_wrpkt();
805 }
806
807 static void defer_packet(int pkttype, ...) {
808     va_list ap1, ap2;
809     va_start(ap1, pkttype);
810     va_start(ap2, pkttype);
811     construct_packet(pkttype, ap1, ap2);
812     s_wrpkt_defer();
813 }
814
815 static int ssh_versioncmp(char *a, char *b) {
816     char *ae, *be;
817     unsigned long av, bv;
818
819     av = strtoul(a, &ae, 10);
820     bv = strtoul(b, &be, 10);
821     if (av != bv) return (av < bv ? -1 : +1);
822     if (*ae == '.') ae++;
823     if (*be == '.') be++;
824     av = strtoul(ae, &ae, 10);
825     bv = strtoul(be, &be, 10);
826     if (av != bv) return (av < bv ? -1 : +1);
827     return 0;
828 }
829
830
831 /*
832  * Utility routines for putting an SSH-protocol `string' and
833  * `uint32' into a SHA state.
834  */
835 #include <stdio.h>
836 static void sha_string(SHA_State *s, void *str, int len) {
837     unsigned char lenblk[4];
838     PUT_32BIT(lenblk, len);
839     SHA_Bytes(s, lenblk, 4);
840     SHA_Bytes(s, str, len);
841 }
842
843 static void sha_uint32(SHA_State *s, unsigned i) {
844     unsigned char intblk[4];
845     PUT_32BIT(intblk, i);
846     SHA_Bytes(s, intblk, 4);
847 }
848
849 /*
850  * SSH2 packet construction functions.
851  */
852 static void ssh2_pkt_ensure(int length) {
853     if (pktout.maxlen < length) {
854         pktout.maxlen = length + 256;
855         pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
856                        srealloc(pktout.data, pktout.maxlen+APIEXTRA));
857         if (!pktout.data)
858             fatalbox("Out of memory");
859     }
860 }
861 static void ssh2_pkt_adddata(void *data, int len) {
862     pktout.length += len;
863     ssh2_pkt_ensure(pktout.length);
864     memcpy(pktout.data+pktout.length-len, data, len);
865 }
866 static void ssh2_pkt_addbyte(unsigned char byte) {
867     ssh2_pkt_adddata(&byte, 1);
868 }
869 static void ssh2_pkt_init(int pkt_type) {
870     pktout.length = 5;
871     ssh2_pkt_addbyte((unsigned char)pkt_type);
872 }
873 static void ssh2_pkt_addbool(unsigned char value) {
874     ssh2_pkt_adddata(&value, 1);
875 }
876 static void ssh2_pkt_adduint32(unsigned long value) {
877     unsigned char x[4];
878     PUT_32BIT(x, value);
879     ssh2_pkt_adddata(x, 4);
880 }
881 static void ssh2_pkt_addstring_start(void) {
882     ssh2_pkt_adduint32(0);
883     pktout.savedpos = pktout.length;
884 }
885 static void ssh2_pkt_addstring_str(char *data) {
886     ssh2_pkt_adddata(data, strlen(data));
887     PUT_32BIT(pktout.data + pktout.savedpos - 4,
888               pktout.length - pktout.savedpos);
889 }
890 static void ssh2_pkt_addstring_data(char *data, int len) {
891     ssh2_pkt_adddata(data, len);
892     PUT_32BIT(pktout.data + pktout.savedpos - 4,
893               pktout.length - pktout.savedpos);
894 }
895 static void ssh2_pkt_addstring(char *data) {
896     ssh2_pkt_addstring_start();
897     ssh2_pkt_addstring_str(data);
898 }
899 static char *ssh2_mpint_fmt(Bignum b, int *len) {
900     unsigned char *p;
901     int i, n = (ssh1_bignum_bitcount(b)+7)/8;
902     p = smalloc(n + 1);
903     if (!p)
904         fatalbox("out of memory");
905     p[0] = 0;
906     for (i = 1; i <= n; i++)
907         p[i] = bignum_byte(b, n-i);
908     i = 0;
909     while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
910         i++;
911     memmove(p, p+i, n+1-i);
912     *len = n+1-i;
913     return p;
914 }
915 static void ssh2_pkt_addmp(Bignum b) {
916     unsigned char *p;
917     int len;
918     p = ssh2_mpint_fmt(b, &len);
919     ssh2_pkt_addstring_start();
920     ssh2_pkt_addstring_data(p, len);
921     sfree(p);
922 }
923
924 /*
925  * Construct an SSH2 final-form packet: compress it, encrypt it,
926  * put the MAC on it. Final packet, ready to be sent, is stored in
927  * pktout.data. Total length is returned.
928  */
929 static int ssh2_pkt_construct(void) {
930     int cipherblk, maclen, padding, i;
931     static unsigned long outgoing_sequence = 0;
932
933     /*
934      * Compress packet payload.
935      */
936 #if 0
937     debug(("Pre-compression payload:\r\n"));
938     for (i = 5; i < pktout.length; i++)
939         debug(("  %02x", (unsigned char)pktout.data[i]));
940     debug(("\r\n"));
941 #endif
942     {
943         unsigned char *newpayload;
944         int newlen;
945         if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
946                                        &newpayload, &newlen)) {
947             pktout.length = 5;
948             ssh2_pkt_adddata(newpayload, newlen);
949             sfree(newpayload);
950         }
951     }
952
953     /*
954      * Add padding. At least four bytes, and must also bring total
955      * length (minus MAC) up to a multiple of the block size.
956      */
957     cipherblk = cscipher ? cscipher->blksize : 8;   /* block size */
958     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
959     padding = 4;
960     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
961     maclen = csmac ? csmac->len : 0;
962     ssh2_pkt_ensure(pktout.length + padding + maclen);
963     pktout.data[4] = padding;
964     for (i = 0; i < padding; i++)
965         pktout.data[pktout.length + i] = random_byte();
966     PUT_32BIT(pktout.data, pktout.length + padding - 4);
967     if (csmac)
968         csmac->generate(pktout.data, pktout.length + padding,
969                         outgoing_sequence);
970     outgoing_sequence++;               /* whether or not we MACed */
971
972 #if 0
973     debug(("Sending packet len=%d\r\n", pktout.length+padding));
974     for (i = 0; i < pktout.length+padding; i++)
975         debug(("  %02x", (unsigned char)pktout.data[i]));
976     debug(("\r\n"));
977 #endif
978
979     if (cscipher)
980         cscipher->encrypt(pktout.data, pktout.length + padding);
981
982     /* Ready-to-send packet starts at pktout.data. We return length. */
983     return pktout.length + padding + maclen;
984 }
985
986 /*
987  * Construct and send an SSH2 packet immediately.
988  */
989 static void ssh2_pkt_send(void) {
990     int len = ssh2_pkt_construct();
991     sk_write(s, pktout.data, len);
992 }
993
994 /*
995  * Construct an SSH2 packet and add it to a deferred data block.
996  * Useful for sending multiple packets in a single sk_write() call,
997  * to prevent a traffic-analysing listener from being able to work
998  * out the length of any particular packet (such as the password
999  * packet).
1000  * 
1001  * Note that because SSH2 sequence-numbers its packets, this can
1002  * NOT be used as an m4-style `defer' allowing packets to be
1003  * constructed in one order and sent in another.
1004  */
1005 static void ssh2_pkt_defer(void) {
1006     int len = ssh2_pkt_construct();
1007     if (deferred_len + len > deferred_size) {
1008         deferred_size = deferred_len + len + 128;
1009         deferred_send_data = srealloc(deferred_send_data, deferred_size);
1010     }
1011     memcpy(deferred_send_data+deferred_len, pktout.data, len);
1012     deferred_len += len;
1013 }
1014
1015 /*
1016  * Send the whole deferred data block constructed by
1017  * ssh2_pkt_defer() or SSH1's defer_packet().
1018  */
1019 static void ssh_pkt_defersend(void) {
1020     sk_write(s, deferred_send_data, deferred_len);
1021     deferred_len = deferred_size = 0;
1022     sfree(deferred_send_data);
1023     deferred_send_data = NULL;
1024 }
1025
1026 #if 0
1027 void bndebug(char *string, Bignum b) {
1028     unsigned char *p;
1029     int i, len;
1030     p = ssh2_mpint_fmt(b, &len);
1031     debug(("%s", string));
1032     for (i = 0; i < len; i++)
1033         debug((" %02x", p[i]));
1034     debug(("\r\n"));
1035     sfree(p);
1036 }
1037 #endif
1038
1039 static void sha_mpint(SHA_State *s, Bignum b) {
1040     unsigned char *p;
1041     int len;
1042     p = ssh2_mpint_fmt(b, &len);
1043     sha_string(s, p, len);
1044     sfree(p);
1045 }
1046
1047 /*
1048  * SSH2 packet decode functions.
1049  */
1050 static unsigned long ssh2_pkt_getuint32(void) {
1051     unsigned long value;
1052     if (pktin.length - pktin.savedpos < 4)
1053         return 0;                      /* arrgh, no way to decline (FIXME?) */
1054     value = GET_32BIT(pktin.data+pktin.savedpos);
1055     pktin.savedpos += 4;
1056     return value;
1057 }
1058 static int ssh2_pkt_getbool(void) {
1059     unsigned long value;
1060     if (pktin.length - pktin.savedpos < 1)
1061         return 0;                      /* arrgh, no way to decline (FIXME?) */
1062     value = pktin.data[pktin.savedpos] != 0;
1063     pktin.savedpos++;
1064     return value;
1065 }
1066 static void ssh2_pkt_getstring(char **p, int *length) {
1067     *p = NULL;
1068     if (pktin.length - pktin.savedpos < 4)
1069         return;
1070     *length = GET_32BIT(pktin.data+pktin.savedpos);
1071     pktin.savedpos += 4;
1072     if (pktin.length - pktin.savedpos < *length)
1073         return;
1074     *p = pktin.data+pktin.savedpos;
1075     pktin.savedpos += *length;
1076 }
1077 static Bignum ssh2_pkt_getmp(void) {
1078     char *p;
1079     int length;
1080     Bignum b;
1081
1082     ssh2_pkt_getstring(&p, &length);
1083     if (!p)
1084         return NULL;
1085     if (p[0] & 0x80) {
1086         bombout(("internal error: Can't handle negative mpints"));
1087         return NULL;
1088     }
1089     b = bignum_from_bytes(p, length);
1090     return b;
1091 }
1092
1093 static int do_ssh_init(unsigned char c) {
1094     static char *vsp;
1095     static char version[10];
1096     static char vstring[80];
1097     static char vlog[sizeof(vstring)+20];
1098     static int i;
1099
1100     crBegin;
1101
1102     /* Search for the string "SSH-" in the input. */
1103     i = 0;
1104     while (1) {
1105         static const int transS[] = { 1, 2, 2, 1 };
1106         static const int transH[] = { 0, 0, 3, 0 };
1107         static const int transminus[] = { 0, 0, 0, -1 };
1108         if (c == 'S') i = transS[i];
1109         else if (c == 'H') i = transH[i];
1110         else if (c == '-') i = transminus[i];
1111         else i = 0;
1112         if (i < 0)
1113             break;
1114         crReturn(1);                   /* get another character */
1115     }
1116
1117     strcpy(vstring, "SSH-");
1118     vsp = vstring+4;
1119     i = 0;
1120     while (1) {
1121         crReturn(1);                   /* get another char */
1122         if (vsp < vstring+sizeof(vstring)-1)
1123             *vsp++ = c;
1124         if (i >= 0) {
1125             if (c == '-') {
1126                 version[i] = '\0';
1127                 i = -1;
1128             } else if (i < sizeof(version)-1)
1129                 version[i++] = c;
1130         }
1131         else if (c == '\n')
1132             break;
1133     }
1134
1135     ssh_agentfwd_enabled = FALSE;
1136     rdpkt2_state.incoming_sequence = 0;
1137
1138     *vsp = 0;
1139     sprintf(vlog, "Server version: %s", vstring);
1140     vlog[strcspn(vlog, "\r\n")] = '\0';
1141     logevent(vlog);
1142
1143     /*
1144      * Server version "1.99" means we can choose whether we use v1
1145      * or v2 protocol. Choice is based on cfg.sshprot.
1146      */
1147     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1148         /*
1149          * This is a v2 server. Begin v2 protocol.
1150          */
1151         char *verstring = "SSH-2.0-PuTTY";
1152         SHA_Init(&exhashbase);
1153         /*
1154          * Hash our version string and their version string.
1155          */
1156         sha_string(&exhashbase, verstring, strlen(verstring));
1157         sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1158         sprintf(vstring, "%s\n", verstring);
1159         sprintf(vlog, "We claim version: %s", verstring);
1160         logevent(vlog);
1161         logevent("Using SSH protocol version 2");
1162         sk_write(s, vstring, strlen(vstring));
1163         ssh_protocol = ssh2_protocol;
1164         ssh_version = 2;
1165         s_rdpkt = ssh2_rdpkt;
1166     } else {
1167         /*
1168          * This is a v1 server. Begin v1 protocol.
1169          */
1170         sprintf(vstring, "SSH-%s-PuTTY\n",
1171                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1172         sprintf(vlog, "We claim version: %s", vstring);
1173         vlog[strcspn(vlog, "\r\n")] = '\0';
1174         logevent(vlog);
1175         logevent("Using SSH protocol version 1");
1176         sk_write(s, vstring, strlen(vstring));
1177         ssh_protocol = ssh1_protocol;
1178         ssh_version = 1;
1179         s_rdpkt = ssh1_rdpkt;
1180     }
1181     ssh_state = SSH_STATE_BEFORE_SIZE;
1182
1183     crFinish(0);
1184 }
1185
1186 static void ssh_gotdata(unsigned char *data, int datalen)
1187 {
1188     crBegin;
1189
1190     /*
1191      * To begin with, feed the characters one by one to the
1192      * protocol initialisation / selection function do_ssh_init().
1193      * When that returns 0, we're done with the initial greeting
1194      * exchange and can move on to packet discipline.
1195      */
1196     while (1) {
1197         int ret;
1198         if (datalen == 0)
1199             crReturnV;                 /* more data please */
1200         ret = do_ssh_init(*data);
1201         data++; datalen--;
1202         if (ret == 0)
1203             break;
1204     }
1205
1206     /*
1207      * We emerge from that loop when the initial negotiation is
1208      * over and we have selected an s_rdpkt function. Now pass
1209      * everything to s_rdpkt, and then pass the resulting packets
1210      * to the proper protocol handler.
1211      */
1212     if (datalen == 0)
1213         crReturnV;
1214     while (1) {
1215         while (datalen > 0) {
1216             if ( s_rdpkt(&data, &datalen) == 0 ) {
1217                 ssh_protocol(NULL, 0, 1);
1218                 if (ssh_state == SSH_STATE_CLOSED) {
1219                     return;
1220                 }
1221             }
1222         }
1223         crReturnV;
1224     }
1225     crFinishV;
1226 }
1227
1228 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1229     if (urgent==3) {
1230         /* A socket error has occurred. */
1231         ssh_state = SSH_STATE_CLOSED;
1232         sk_close(s);
1233         s = NULL;
1234         connection_fatal(data);
1235         return 0;
1236     } else if (!len) {
1237         /* Connection has closed. */
1238         ssh_state = SSH_STATE_CLOSED;
1239         sk_close(s);
1240         s = NULL;
1241         return 0;
1242     }
1243     ssh_gotdata (data, len);
1244     if (ssh_state == SSH_STATE_CLOSED) {
1245         if (s) {
1246             sk_close(s);
1247             s = NULL;
1248         }
1249         return 0;
1250     }
1251     return 1;
1252 }
1253
1254 /*
1255  * Connect to specified host and port.
1256  * Returns an error message, or NULL on success.
1257  * Also places the canonical host name into `realhost'.
1258  */
1259 static char *connect_to_host(char *host, int port, char **realhost)
1260 {
1261     SockAddr addr;
1262     char *err;
1263 #ifdef FWHACK
1264     char *FWhost;
1265     int FWport;
1266 #endif
1267
1268     savedhost = smalloc(1+strlen(host));
1269     if (!savedhost)
1270         fatalbox("Out of memory");
1271     strcpy(savedhost, host);
1272
1273     if (port < 0)
1274         port = 22;                     /* default ssh port */
1275     savedport = port;
1276
1277 #ifdef FWHACK
1278     FWhost = host;
1279     FWport = port;
1280     host = FWSTR;
1281     port = 23;
1282 #endif
1283
1284     /*
1285      * Try to find host.
1286      */
1287     addr = sk_namelookup(host, realhost);
1288     if ( (err = sk_addr_error(addr)) )
1289         return err;
1290
1291 #ifdef FWHACK
1292     *realhost = FWhost;
1293 #endif
1294
1295     /*
1296      * Open socket.
1297      */
1298     s = sk_new(addr, port, 0, 1, ssh_receive);
1299     if ( (err = sk_socket_error(s)) )
1300         return err;
1301
1302 #ifdef FWHACK
1303     sk_write(s, "connect ", 8);
1304     sk_write(s, FWhost, strlen(FWhost));
1305     {
1306         char buf[20];
1307         sprintf(buf, " %d\n", FWport);
1308         sk_write(s, buf, strlen(buf));
1309     }
1310 #endif
1311
1312     return NULL;
1313 }
1314
1315 /*
1316  * Handle the key exchange and user authentication phases.
1317  */
1318 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1319 {
1320     int i, j, len;
1321     unsigned char *rsabuf, *keystr1, *keystr2;
1322     unsigned char cookie[8];
1323     struct RSAKey servkey, hostkey;
1324     struct MD5Context md5c;
1325     static unsigned long supported_ciphers_mask, supported_auths_mask;
1326     static int tried_publickey;
1327     static unsigned char session_id[16];
1328     int cipher_type;
1329     static char username[100];
1330
1331     crBegin;
1332
1333     if (!ispkt) crWaitUntil(ispkt);
1334
1335     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1336         bombout(("Public key packet not received"));
1337         crReturn(0);
1338     }
1339
1340     logevent("Received public keys");
1341
1342     memcpy(cookie, pktin.body, 8);
1343
1344     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1345     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1346
1347     /*
1348      * Log the host key fingerprint.
1349      */
1350     {
1351         char logmsg[80];
1352         logevent("Host key fingerprint is:");
1353         strcpy(logmsg, "      ");
1354         hostkey.comment = NULL;
1355         rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1356                         &hostkey);
1357         logevent(logmsg);
1358     }
1359
1360     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1361     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1362
1363     MD5Init(&md5c);
1364     MD5Update(&md5c, keystr2, hostkey.bytes);
1365     MD5Update(&md5c, keystr1, servkey.bytes);
1366     MD5Update(&md5c, pktin.body, 8);
1367     MD5Final(session_id, &md5c);
1368
1369     for (i=0; i<32; i++)
1370         session_key[i] = random_byte();
1371
1372     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1373
1374     rsabuf = smalloc(len);
1375     if (!rsabuf)
1376         fatalbox("Out of memory");
1377
1378     /*
1379      * Verify the host key.
1380      */
1381     {
1382         /*
1383          * First format the key into a string.
1384          */
1385         int len = rsastr_len(&hostkey);
1386         char fingerprint[100];
1387         char *keystr = smalloc(len);
1388         if (!keystr)
1389             fatalbox("Out of memory");
1390         rsastr_fmt(keystr, &hostkey);
1391         rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1392         verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1393         sfree(keystr);
1394     }
1395
1396     for (i=0; i<32; i++) {
1397         rsabuf[i] = session_key[i];
1398         if (i < 16)
1399             rsabuf[i] ^= session_id[i];
1400     }
1401
1402     if (hostkey.bytes > servkey.bytes) {
1403         rsaencrypt(rsabuf, 32, &servkey);
1404         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1405     } else {
1406         rsaencrypt(rsabuf, 32, &hostkey);
1407         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1408     }
1409
1410     logevent("Encrypted session key");
1411
1412     switch (cfg.cipher) {
1413       case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1414       case CIPHER_DES:      cipher_type = SSH_CIPHER_DES;      break;
1415       case CIPHER_3DES:     cipher_type = SSH_CIPHER_3DES;     break;
1416       case CIPHER_AES:
1417         c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1418         cipher_type = SSH_CIPHER_3DES;
1419         break;
1420     }
1421     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1422         c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1423         cipher_type = SSH_CIPHER_3DES;
1424     }
1425     switch (cipher_type) {
1426       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1427       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1428       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1429     }
1430
1431     send_packet(SSH1_CMSG_SESSION_KEY,
1432                 PKT_CHAR, cipher_type,
1433                 PKT_DATA, cookie, 8,
1434                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1435                 PKT_DATA, rsabuf, len,
1436                 PKT_INT, 0,
1437                 PKT_END);
1438
1439     logevent("Trying to enable encryption...");
1440
1441     sfree(rsabuf);
1442
1443     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1444              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1445              &ssh_3des;
1446     cipher->sesskey(session_key);
1447
1448     crWaitUntil(ispkt);
1449
1450     if (pktin.type != SSH1_SMSG_SUCCESS) {
1451         bombout(("Encryption not successfully enabled"));
1452         crReturn(0);
1453     }
1454
1455     logevent("Successfully started encryption");
1456
1457     fflush(stdout);
1458     {
1459         static int pos = 0;
1460         static char c;
1461         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1462             c_write_str("login as: ");
1463             ssh_send_ok = 1;
1464             while (pos >= 0) {
1465                 crWaitUntil(!ispkt);
1466                 while (inlen--) switch (c = *in++) {
1467                   case 10: case 13:
1468                     username[pos] = 0;
1469                     pos = -1;
1470                     break;
1471                   case 8: case 127:
1472                     if (pos > 0) {
1473                         c_write_str("\b \b");
1474                         pos--;
1475                     }
1476                     break;
1477                   case 21: case 27:
1478                     while (pos > 0) {
1479                         c_write_str("\b \b");
1480                         pos--;
1481                     }
1482                     break;
1483                   case 3: case 4:
1484                     random_save_seed();
1485                     exit(0);
1486                     break;
1487                   default:
1488                     if (((c >= ' ' && c <= '~') ||
1489                          ((unsigned char)c >= 160)) && pos < 40) {
1490                         username[pos++] = c;
1491                         c_write(&c, 1);
1492                     }
1493                     break;
1494                 }
1495             }
1496             c_write_str("\r\n");
1497             username[strcspn(username, "\n\r")] = '\0';
1498         } else {
1499             strncpy(username, cfg.username, 99);
1500             username[99] = '\0';
1501         }
1502
1503         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1504         {
1505             char userlog[22+sizeof(username)];
1506             sprintf(userlog, "Sent username \"%s\"", username);
1507             logevent(userlog);
1508             if (flags & FLAG_INTERACTIVE &&
1509                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1510                 strcat(userlog, "\r\n");
1511                 c_write_str(userlog);
1512             }
1513         }
1514     }
1515
1516     crWaitUntil(ispkt);
1517
1518     tried_publickey = 0;
1519
1520     while (pktin.type == SSH1_SMSG_FAILURE) {
1521         static char password[100];
1522         static char prompt[200];
1523         static int pos;
1524         static char c;
1525         static int pwpkt_type;
1526         /*
1527          * Show password prompt, having first obtained it via a TIS
1528          * or CryptoCard exchange if we're doing TIS or CryptoCard
1529          * authentication.
1530          */
1531         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1532         if (agent_exists()) {
1533             /*
1534              * Attempt RSA authentication using Pageant.
1535              */
1536             static unsigned char request[5], *response, *p;
1537             static int responselen;
1538             static int i, nkeys;
1539             static int authed = FALSE;
1540             void *r;
1541
1542             logevent("Pageant is running. Requesting keys.");
1543
1544             /* Request the keys held by the agent. */
1545             PUT_32BIT(request, 1);
1546             request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
1547             agent_query(request, 5, &r, &responselen);
1548             response = (unsigned char *)r;
1549             if (response) {
1550                 p = response + 5;
1551                 nkeys = GET_32BIT(p); p += 4;
1552                 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1553                     logevent(buf); }
1554                 for (i = 0; i < nkeys; i++) {
1555                     static struct RSAKey key;
1556                     static Bignum challenge;
1557                     static char *commentp;
1558                     static int commentlen;
1559
1560                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1561                         logevent(buf); }
1562                     p += 4;
1563                     p += ssh1_read_bignum(p, &key.exponent);
1564                     p += ssh1_read_bignum(p, &key.modulus);
1565                     commentlen = GET_32BIT(p); p += 4;
1566                     commentp = p; p += commentlen;
1567                     send_packet(SSH1_CMSG_AUTH_RSA,
1568                                 PKT_BIGNUM, key.modulus, PKT_END);
1569                     crWaitUntil(ispkt);
1570                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1571                         logevent("Key refused");
1572                         continue;
1573                     }
1574                     logevent("Received RSA challenge");
1575                     ssh1_read_bignum(pktin.body, &challenge);
1576                     {
1577                         char *agentreq, *q, *ret;
1578                         int len, retlen;
1579                         len = 1 + 4;   /* message type, bit count */
1580                         len += ssh1_bignum_length(key.exponent);
1581                         len += ssh1_bignum_length(key.modulus);
1582                         len += ssh1_bignum_length(challenge);
1583                         len += 16;     /* session id */
1584                         len += 4;      /* response format */
1585                         agentreq = smalloc(4 + len);
1586                         PUT_32BIT(agentreq, len);
1587                         q = agentreq + 4;
1588                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
1589                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1590                         q += 4;
1591                         q += ssh1_write_bignum(q, key.exponent);
1592                         q += ssh1_write_bignum(q, key.modulus);
1593                         q += ssh1_write_bignum(q, challenge);
1594                         memcpy(q, session_id, 16); q += 16;
1595                         PUT_32BIT(q, 1);   /* response format */
1596                         agent_query(agentreq, len+4, &ret, &retlen);
1597                         sfree(agentreq);
1598                         if (ret) {
1599                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
1600                                 logevent("Sending Pageant's response");
1601                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1602                                             PKT_DATA, ret+5, 16, PKT_END);
1603                                 sfree(ret);
1604                                 crWaitUntil(ispkt);
1605                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1606                                     logevent("Pageant's response accepted");
1607                                     if (flags & FLAG_VERBOSE) {
1608                                         c_write_str("Authenticated using RSA key \"");
1609                                         c_write(commentp, commentlen);
1610                                         c_write_str("\" from agent\r\n");
1611                                     }
1612                                     authed = TRUE;
1613                                 } else
1614                                     logevent("Pageant's response not accepted");
1615                             } else {
1616                                 logevent("Pageant failed to answer challenge");
1617                                 sfree(ret);
1618                             }
1619                         } else {
1620                             logevent("No reply received from Pageant");
1621                         }
1622                     }
1623                     freebn(key.exponent);
1624                     freebn(key.modulus);
1625                     freebn(challenge);
1626                     if (authed)
1627                         break;
1628                 }
1629             }
1630             if (authed)
1631                 break;
1632         }
1633         if (*cfg.keyfile && !tried_publickey)
1634             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1635
1636         if (pktin.type == SSH1_SMSG_FAILURE &&
1637             cfg.try_tis_auth &&
1638             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1639             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1640             logevent("Requested TIS authentication");
1641             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1642             crWaitUntil(ispkt);
1643             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1644                 logevent("TIS authentication declined");
1645                 if (flags & FLAG_INTERACTIVE)
1646                     c_write_str("TIS authentication refused.\r\n");
1647             } else {
1648                 int challengelen = ((pktin.body[0] << 24) |
1649                                     (pktin.body[1] << 16) |
1650                                     (pktin.body[2] << 8) |
1651                                     (pktin.body[3]));
1652                 logevent("Received TIS challenge");
1653                 if (challengelen > sizeof(prompt)-1)
1654                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1655                 memcpy(prompt, pktin.body+4, challengelen);
1656                 prompt[challengelen] = '\0';
1657             }
1658         }
1659         if (pktin.type == SSH1_SMSG_FAILURE &&
1660             cfg.try_tis_auth &&
1661             (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1662             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1663             logevent("Requested CryptoCard authentication");
1664             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1665             crWaitUntil(ispkt);
1666             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1667                 logevent("CryptoCard authentication declined");
1668                 c_write_str("CryptoCard authentication refused.\r\n");
1669             } else {
1670                 int challengelen = ((pktin.body[0] << 24) |
1671                                     (pktin.body[1] << 16) |
1672                                     (pktin.body[2] << 8) |
1673                                     (pktin.body[3]));
1674                 logevent("Received CryptoCard challenge");
1675                 if (challengelen > sizeof(prompt)-1)
1676                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1677                 memcpy(prompt, pktin.body+4, challengelen);
1678                 strncpy(prompt + challengelen, "\r\nResponse : ",
1679                         sizeof(prompt)-challengelen);
1680                 prompt[sizeof(prompt)-1] = '\0';
1681             }
1682         }
1683         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1684             sprintf(prompt, "%.90s@%.90s's password: ",
1685                     username, savedhost);
1686         }
1687         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1688             char *comment = NULL;
1689             if (flags & FLAG_VERBOSE)
1690                 c_write_str("Trying public key authentication.\r\n");
1691             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1692                 if (flags & FLAG_VERBOSE)
1693                     c_write_str("No passphrase required.\r\n");
1694                 goto tryauth;
1695             }
1696             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1697             sfree(comment);
1698         }
1699
1700         if (ssh_get_password) {
1701             if (!ssh_get_password(prompt, password, sizeof(password))) {
1702                 /*
1703                  * get_password failed to get a password (for
1704                  * example because one was supplied on the command
1705                  * line which has already failed to work).
1706                  * Terminate.
1707                  */
1708                 logevent("No more passwords to try");
1709                 ssh_state = SSH_STATE_CLOSED;
1710                 crReturn(1);
1711             }
1712         } else {
1713             c_write_str(prompt);
1714             pos = 0;
1715             ssh_send_ok = 1;
1716             while (pos >= 0) {
1717                 crWaitUntil(!ispkt);
1718                 while (inlen--) switch (c = *in++) {
1719                   case 10: case 13:
1720                     password[pos] = 0;
1721                     pos = -1;
1722                     break;
1723                   case 8: case 127:
1724                     if (pos > 0)
1725                         pos--;
1726                     break;
1727                   case 21: case 27:
1728                     pos = 0;
1729                     break;
1730                   case 3: case 4:
1731                     random_save_seed();
1732                     exit(0);
1733                     break;
1734                   default:
1735                     if (((c >= ' ' && c <= '~') ||
1736                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1737                         password[pos++] = c;
1738                     break;
1739                 }
1740             }
1741             c_write_str("\r\n");
1742         }
1743
1744         tryauth:
1745         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1746             /*
1747              * Try public key authentication with the specified
1748              * key file.
1749              */
1750             static struct RSAKey pubkey;
1751             static Bignum challenge, response;
1752             static int i;
1753             static unsigned char buffer[32];
1754
1755             tried_publickey = 1;
1756             i = loadrsakey(cfg.keyfile, &pubkey, password);
1757             if (i == 0) {
1758                 c_write_str("Couldn't load public key from ");
1759                 c_write_str(cfg.keyfile);
1760                 c_write_str(".\r\n");
1761                 continue;              /* go and try password */
1762             }
1763             if (i == -1) {
1764                 c_write_str("Wrong passphrase.\r\n");
1765                 tried_publickey = 0;
1766                 continue;              /* try again */
1767             }
1768
1769             /*
1770              * Send a public key attempt.
1771              */
1772             send_packet(SSH1_CMSG_AUTH_RSA,
1773                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1774
1775             crWaitUntil(ispkt);
1776             if (pktin.type == SSH1_SMSG_FAILURE) {
1777                 c_write_str("Server refused our public key.\r\n");
1778                 continue;              /* go and try password */
1779             }
1780             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1781                 bombout(("Bizarre response to offer of public key"));
1782                 crReturn(0);
1783             }
1784             ssh1_read_bignum(pktin.body, &challenge);
1785             response = rsadecrypt(challenge, &pubkey);
1786             freebn(pubkey.private_exponent);   /* burn the evidence */
1787
1788             for (i = 0; i < 32; i++) {
1789                 buffer[i] = bignum_byte(response, 31-i);
1790             }
1791
1792             MD5Init(&md5c);
1793             MD5Update(&md5c, buffer, 32);
1794             MD5Update(&md5c, session_id, 16);
1795             MD5Final(buffer, &md5c);
1796
1797             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1798                         PKT_DATA, buffer, 16, PKT_END);
1799
1800             crWaitUntil(ispkt);
1801             if (pktin.type == SSH1_SMSG_FAILURE) {
1802                 if (flags & FLAG_VERBOSE)
1803                     c_write_str("Failed to authenticate with our public key.\r\n");
1804                 continue;              /* go and try password */
1805             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1806                 bombout(("Bizarre response to RSA authentication response"));
1807                 crReturn(0);
1808             }
1809
1810             break;                     /* we're through! */
1811         } else {
1812             if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1813                 /*
1814                  * Defence against traffic analysis: we send a
1815                  * whole bunch of packets containing strings of
1816                  * different lengths. One of these strings is the
1817                  * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1818                  * The others are all random data in
1819                  * SSH1_MSG_IGNORE packets. This way a passive
1820                  * listener can't tell which is the password, and
1821                  * hence can't deduce the password length.
1822                  * 
1823                  * Anybody with a password length greater than 16
1824                  * bytes is going to have enough entropy in their
1825                  * password that a listener won't find it _that_
1826                  * much help to know how long it is. So what we'll
1827                  * do is:
1828                  * 
1829                  *  - if password length < 16, we send 15 packets
1830                  *    containing string lengths 1 through 15
1831                  * 
1832                  *  - otherwise, we let N be the nearest multiple
1833                  *    of 8 below the password length, and send 8
1834                  *    packets containing string lengths N through
1835                  *    N+7. This won't obscure the order of
1836                  *    magnitude of the password length, but it will
1837                  *    introduce a bit of extra uncertainty.
1838                  */
1839                 int bottom, top, pwlen, i;
1840                 char *randomstr;
1841
1842                 pwlen = strlen(password);
1843                 if (pwlen < 16) {
1844                     bottom = 1;
1845                     top = 15;
1846                 } else {
1847                     bottom = pwlen &~ 7;
1848                     top = bottom + 7;
1849                 }
1850
1851                 assert(pwlen >= bottom && pwlen <= top);
1852
1853                 randomstr = smalloc(top+1);
1854
1855                 for (i = bottom; i <= top; i++) {
1856                     if (i == pwlen)
1857                         defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1858                     else {
1859                         for (j = 0; j < i; j++) {
1860                             do {
1861                                 randomstr[j] = random_byte();
1862                             } while (randomstr[j] == '\0');
1863                         }
1864                         randomstr[i] = '\0';
1865                         defer_packet(SSH1_MSG_IGNORE,
1866                                      PKT_STR, randomstr, PKT_END);
1867                     }
1868                 }
1869                 ssh_pkt_defersend();
1870             } else {
1871                 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1872             }
1873         }
1874         logevent("Sent password");
1875         memset(password, 0, strlen(password));
1876         crWaitUntil(ispkt);
1877         if (pktin.type == SSH1_SMSG_FAILURE) {
1878             if (flags & FLAG_VERBOSE)
1879                 c_write_str("Access denied\r\n");
1880             logevent("Authentication refused");
1881         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1882             logevent("Received disconnect request");
1883             ssh_state = SSH_STATE_CLOSED;
1884             crReturn(1);
1885         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1886             bombout(("Strange packet received, type %d", pktin.type));
1887             crReturn(0);
1888         }
1889     }
1890
1891     logevent("Authentication successful");
1892
1893     crFinish(1);
1894 }
1895
1896 void sshfwd_close(struct ssh_channel *c) {
1897     if (c) {
1898         if (ssh_version == 1) {
1899             send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1900         } else {
1901             ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1902             ssh2_pkt_adduint32(c->remoteid);
1903             ssh2_pkt_send();
1904         }
1905         c->closes = 1;
1906         if (c->type == CHAN_X11) {
1907             c->u.x11.s = NULL;
1908             logevent("X11 connection terminated");
1909         }
1910     }
1911 }
1912
1913 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1914     if (ssh_version == 1) {
1915         send_packet(SSH1_MSG_CHANNEL_DATA,
1916                     PKT_INT, c->remoteid,
1917                     PKT_INT, len,
1918                     PKT_DATA, buf, len,
1919                     PKT_END);
1920     } else {
1921         ssh2_add_channel_data(c, buf, len);
1922         ssh2_try_send(c);
1923     }
1924 }
1925
1926 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1927     crBegin;
1928
1929     random_init();
1930
1931     while (!do_ssh1_login(in, inlen, ispkt)) {
1932         crReturnV;
1933     }
1934     if (ssh_state == SSH_STATE_CLOSED)
1935         crReturnV;
1936
1937     if (cfg.agentfwd && agent_exists()) {
1938         logevent("Requesting agent forwarding");
1939         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1940         do { crReturnV; } while (!ispkt);
1941         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1942             bombout(("Protocol confusion"));
1943             crReturnV;
1944         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1945             logevent("Agent forwarding refused");
1946         } else {
1947             logevent("Agent forwarding enabled");
1948             ssh_agentfwd_enabled = TRUE;
1949         }
1950     }
1951
1952     if (cfg.x11_forward) {
1953         char proto[20], data[64];
1954         logevent("Requesting X11 forwarding");
1955         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1956         send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING, 
1957                     PKT_STR, proto, PKT_STR, data,
1958                     PKT_INT, 0,
1959                     PKT_END);
1960         do { crReturnV; } while (!ispkt);
1961         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1962             bombout(("Protocol confusion"));
1963             crReturnV;
1964         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1965             logevent("X11 forwarding refused");
1966         } else {
1967             logevent("X11 forwarding enabled");
1968             ssh_X11_fwd_enabled = TRUE;
1969         }
1970     }
1971
1972     if (!cfg.nopty) {
1973         send_packet(SSH1_CMSG_REQUEST_PTY,
1974                     PKT_STR, cfg.termtype,
1975                     PKT_INT, rows, PKT_INT, cols,
1976                     PKT_INT, 0, PKT_INT, 0,
1977                     PKT_CHAR, 0,
1978                     PKT_END);
1979         ssh_state = SSH_STATE_INTERMED;
1980         do { crReturnV; } while (!ispkt);
1981         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1982             bombout(("Protocol confusion"));
1983             crReturnV;
1984         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1985             c_write_str("Server refused to allocate pty\r\n");
1986             ssh_editing = ssh_echoing = 1;
1987         }
1988         logevent("Allocated pty");
1989     } else {
1990         ssh_editing = ssh_echoing = 1;
1991     }
1992
1993     if (cfg.compression) {
1994         send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1995         do { crReturnV; } while (!ispkt);
1996         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1997             bombout(("Protocol confusion"));
1998             crReturnV;
1999         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2000             c_write_str("Server refused to compress\r\n");
2001         }
2002         logevent("Started compression");
2003         ssh1_compressing = TRUE;
2004         zlib_compress_init();
2005         zlib_decompress_init();
2006     }
2007
2008     if (*cfg.remote_cmd)
2009         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
2010     else
2011         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2012     logevent("Started session");
2013
2014     ssh_state = SSH_STATE_SESSION;
2015     if (size_needed)
2016         ssh_size();
2017     if (eof_needed)
2018         ssh_special(TS_EOF);
2019
2020     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
2021     ssh_send_ok = 1;
2022     ssh_channels = newtree234(ssh_channelcmp);
2023     while (1) {
2024         crReturnV;
2025         if (ispkt) {
2026             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2027                 pktin.type == SSH1_SMSG_STDERR_DATA) {
2028                 long len = GET_32BIT(pktin.body);
2029                 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2030                              pktin.body+4, len);
2031             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2032                 ssh_state = SSH_STATE_CLOSED;
2033                 logevent("Received disconnect request");
2034                 crReturnV;
2035             } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2036                 /* Remote side is trying to open a channel to talk to our
2037                  * X-Server. Give them back a local channel number. */
2038                 unsigned i;
2039                 struct ssh_channel *c, *d;
2040                 enum234 e;
2041
2042                 logevent("Received X11 connect request");
2043                 /* Refuse if X11 forwarding is disabled. */
2044                 if (!ssh_X11_fwd_enabled) {
2045                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2046                                 PKT_INT, GET_32BIT(pktin.body),
2047                                 PKT_END);
2048                     logevent("Rejected X11 connect request");
2049                 } else {
2050                     c = smalloc(sizeof(struct ssh_channel));
2051
2052                     if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2053                       logevent("opening X11 forward connection failed");
2054                       sfree(c);
2055                       send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2056                                   PKT_INT, GET_32BIT(pktin.body),
2057                                   PKT_END);
2058                     } else {
2059                       logevent("opening X11 forward connection succeeded");
2060                       for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
2061                           if (d->localid > i)
2062                               break;     /* found a free number */
2063                           i = d->localid + 1;
2064                       }
2065                       c->remoteid = GET_32BIT(pktin.body);
2066                       c->localid = i;
2067                       c->closes = 0;
2068                       c->type = CHAN_X11;   /* identify channel type */
2069                       add234(ssh_channels, c);
2070                       send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2071                                   PKT_INT, c->remoteid, PKT_INT, c->localid,
2072                                   PKT_END);
2073                       logevent("Opened X11 forward channel");
2074                     }
2075                 }
2076             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2077                 /* Remote side is trying to open a channel to talk to our
2078                  * agent. Give them back a local channel number. */
2079                 unsigned i;
2080                 struct ssh_channel *c;
2081                 enum234 e;
2082
2083                 /* Refuse if agent forwarding is disabled. */
2084                 if (!ssh_agentfwd_enabled) {
2085                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2086                                 PKT_INT, GET_32BIT(pktin.body),
2087                                 PKT_END);
2088                 } else {
2089                     i = 1;
2090                     for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2091                         if (c->localid > i)
2092                             break;     /* found a free number */
2093                         i = c->localid + 1;
2094                     }
2095                     c = smalloc(sizeof(struct ssh_channel));
2096                     c->remoteid = GET_32BIT(pktin.body);
2097                     c->localid = i;
2098                     c->closes = 0;
2099                     c->type = CHAN_AGENT;   /* identify channel type */
2100                     c->u.a.lensofar = 0;
2101                     add234(ssh_channels, c);
2102                     send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2103                                 PKT_INT, c->remoteid, PKT_INT, c->localid,
2104                                 PKT_END);
2105                 }
2106             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2107                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2108                 /* Remote side closes a channel. */
2109                 unsigned i = GET_32BIT(pktin.body);
2110                 struct ssh_channel *c;
2111                 c = find234(ssh_channels, &i, ssh_channelfind);
2112                 if (c) {
2113                     int closetype;
2114                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2115                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2116                     if ((c->closes == 0) && (c->type == CHAN_X11)) {
2117                         logevent("X11 connection closed");
2118                         assert(c->u.x11.s != NULL);
2119                         x11_close(c->u.x11.s);
2120                         c->u.x11.s = NULL;
2121                     }
2122                     c->closes |= closetype;
2123                     if (c->closes == 3) {
2124                         del234(ssh_channels, c);
2125                         sfree(c);
2126                     }
2127                 }
2128             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2129                 /* Data sent down one of our channels. */
2130                 int i = GET_32BIT(pktin.body);
2131                 int len = GET_32BIT(pktin.body+4);
2132                 unsigned char *p = pktin.body+8;
2133                 struct ssh_channel *c;
2134                 c = find234(ssh_channels, &i, ssh_channelfind);
2135                 if (c) {
2136                     switch(c->type) {
2137                       case CHAN_X11:
2138                         x11_send(c->u.x11.s, p, len);
2139                         break;
2140                       case CHAN_AGENT:
2141                         /* Data for an agent message. Buffer it. */
2142                         while (len > 0) {
2143                             if (c->u.a.lensofar < 4) {
2144                                 int l = min(4 - c->u.a.lensofar, len);
2145                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2146                                 p += l; len -= l; c->u.a.lensofar += l;
2147                             }
2148                             if (c->u.a.lensofar == 4) {
2149                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2150                                 c->u.a.message = smalloc(c->u.a.totallen);
2151                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
2152                             }
2153                             if (c->u.a.lensofar >= 4 && len > 0) {
2154                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2155                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2156                                 p += l; len -= l; c->u.a.lensofar += l;
2157                             }
2158                             if (c->u.a.lensofar == c->u.a.totallen) {
2159                                 void *reply, *sentreply;
2160                                 int replylen;
2161                                 agent_query(c->u.a.message, c->u.a.totallen,
2162                                             &reply, &replylen);
2163                                 if (reply)
2164                                     sentreply = reply;
2165                                 else {
2166                                     /* Fake SSH_AGENT_FAILURE. */
2167                                     sentreply = "\0\0\0\1\5";
2168                                     replylen = 5;
2169                                 }
2170                                 send_packet(SSH1_MSG_CHANNEL_DATA,
2171                                             PKT_INT, c->remoteid,
2172                                             PKT_INT, replylen,
2173                                             PKT_DATA, sentreply, replylen,
2174                                             PKT_END);
2175                                 if (reply)
2176                                     sfree(reply);
2177                                 sfree(c->u.a.message);
2178                                 c->u.a.lensofar = 0;
2179                             }
2180                         }
2181                         break;
2182                     }
2183                 }                
2184             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2185                 /* may be from EXEC_SHELL on some servers */
2186             } else if (pktin.type == SSH1_SMSG_FAILURE) {
2187                 /* may be from EXEC_SHELL on some servers
2188                  * if no pty is available or in other odd cases. Ignore */
2189             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2190                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2191             } else {
2192                 bombout(("Strange packet received: type %d", pktin.type));
2193                 crReturnV;
2194             }
2195         } else {
2196             while (inlen > 0) {
2197                 int len = min(inlen, 512);
2198                 send_packet(SSH1_CMSG_STDIN_DATA,
2199                             PKT_INT, len, PKT_DATA, in, len, PKT_END);
2200                 in += len;
2201                 inlen -= len;
2202             }
2203         }
2204     }
2205
2206     crFinishV;
2207 }
2208
2209 /*
2210  * Utility routine for decoding comma-separated strings in KEXINIT.
2211  */
2212 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2213     int needlen = strlen(needle);
2214     while (1) {
2215         /*
2216          * Is it at the start of the string?
2217          */
2218         if (haylen >= needlen &&       /* haystack is long enough */
2219             !memcmp(needle, haystack, needlen) &&    /* initial match */
2220             (haylen == needlen || haystack[needlen] == ',')
2221                                        /* either , or EOS follows */
2222             )
2223             return 1;
2224         /*
2225          * If not, search for the next comma and resume after that.
2226          * If no comma found, terminate.
2227          */
2228         while (haylen > 0 && *haystack != ',')
2229             haylen--, haystack++;
2230         if (haylen == 0)
2231             return 0;
2232         haylen--, haystack++;          /* skip over comma itself */
2233     }
2234 }
2235
2236 /*
2237  * SSH2 key creation method.
2238  */
2239 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2240     SHA_State s;
2241     /* First 20 bytes. */
2242     SHA_Init(&s);
2243     sha_mpint(&s, K);
2244     SHA_Bytes(&s, H, 20);
2245     SHA_Bytes(&s, &chr, 1);
2246     SHA_Bytes(&s, sessid, 20);
2247     SHA_Final(&s, keyspace);
2248     /* Next 20 bytes. */
2249     SHA_Init(&s);
2250     sha_mpint(&s, K);
2251     SHA_Bytes(&s, H, 20);
2252     SHA_Bytes(&s, keyspace, 20);
2253     SHA_Final(&s, keyspace+20);
2254 }
2255
2256 /*
2257  * Handle the SSH2 transport layer.
2258  */
2259 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2260 {
2261     static int i, j, len, nbits;
2262     static char *str;
2263     static Bignum p, g, e, f, K;
2264     static int kex_init_value, kex_reply_value;
2265     static const struct ssh_mac **maclist;
2266     static int nmacs;
2267     static const struct ssh2_cipher *cscipher_tobe = NULL;
2268     static const struct ssh2_cipher *sccipher_tobe = NULL;
2269     static const struct ssh_mac *csmac_tobe = NULL;
2270     static const struct ssh_mac *scmac_tobe = NULL;
2271     static const struct ssh_compress *cscomp_tobe = NULL;
2272     static const struct ssh_compress *sccomp_tobe = NULL;
2273     static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2274     static int hostkeylen, siglen;
2275     static void *hkey;                 /* actual host key */
2276     static unsigned char exchange_hash[20];
2277     static unsigned char keyspace[40];
2278     static const struct ssh2_ciphers *preferred_cipher;
2279     static const struct ssh_compress *preferred_comp;
2280     static int first_kex;
2281
2282     crBegin;
2283     random_init();
2284     first_kex = 1;
2285
2286     /*
2287      * Set up the preferred cipher and compression.
2288      */
2289     if (cfg.cipher == CIPHER_BLOWFISH) {
2290         preferred_cipher = &ssh2_blowfish;
2291     } else if (cfg.cipher == CIPHER_DES) {
2292         logevent("Single DES not supported in SSH2; using 3DES");
2293         preferred_cipher = &ssh2_3des;
2294     } else if (cfg.cipher == CIPHER_3DES) {
2295         preferred_cipher = &ssh2_3des;
2296     } else if (cfg.cipher == CIPHER_AES) {
2297         preferred_cipher = &ssh2_aes;
2298     } else {
2299         /* Shouldn't happen, but we do want to initialise to _something_. */
2300         preferred_cipher = &ssh2_3des;
2301     }
2302     if (cfg.compression)
2303         preferred_comp = &ssh_zlib;
2304     else
2305         preferred_comp = &ssh_comp_none;
2306
2307     /*
2308      * Be prepared to work around the buggy MAC problem.
2309      */
2310     if (cfg.buggymac)
2311         maclist = buggymacs, nmacs = lenof(buggymacs);
2312     else
2313         maclist = macs, nmacs = lenof(macs);
2314
2315     begin_key_exchange:
2316     /*
2317      * Construct and send our key exchange packet.
2318      */
2319     ssh2_pkt_init(SSH2_MSG_KEXINIT);
2320     for (i = 0; i < 16; i++)
2321         ssh2_pkt_addbyte((unsigned char)random_byte());
2322     /* List key exchange algorithms. */
2323     ssh2_pkt_addstring_start();
2324     for (i = 0; i < lenof(kex_algs); i++) {
2325         ssh2_pkt_addstring_str(kex_algs[i]->name);
2326         if (i < lenof(kex_algs)-1)
2327             ssh2_pkt_addstring_str(",");
2328     }
2329     /* List server host key algorithms. */
2330     ssh2_pkt_addstring_start();
2331     for (i = 0; i < lenof(hostkey_algs); i++) {
2332         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2333         if (i < lenof(hostkey_algs)-1)
2334             ssh2_pkt_addstring_str(",");
2335     }
2336     /* List client->server encryption algorithms. */
2337     ssh2_pkt_addstring_start();
2338     for (i = 0; i < lenof(ciphers)+1; i++) {
2339         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2340         for (j = 0; j < c->nciphers; j++) {
2341             ssh2_pkt_addstring_str(c->list[j]->name);
2342             if (i < lenof(ciphers) || j < c->nciphers-1)
2343                 ssh2_pkt_addstring_str(",");
2344         }
2345     }
2346     /* List server->client encryption algorithms. */
2347     ssh2_pkt_addstring_start();
2348     for (i = 0; i < lenof(ciphers)+1; i++) {
2349         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2350         for (j = 0; j < c->nciphers; j++) {
2351             ssh2_pkt_addstring_str(c->list[j]->name);
2352             if (i < lenof(ciphers) || j < c->nciphers-1)
2353                 ssh2_pkt_addstring_str(",");
2354         }
2355     }
2356     /* List client->server MAC algorithms. */
2357     ssh2_pkt_addstring_start();
2358     for (i = 0; i < nmacs; i++) {
2359         ssh2_pkt_addstring_str(maclist[i]->name);
2360         if (i < nmacs-1)
2361             ssh2_pkt_addstring_str(",");
2362     }
2363     /* List server->client MAC algorithms. */
2364     ssh2_pkt_addstring_start();
2365     for (i = 0; i < nmacs; i++) {
2366         ssh2_pkt_addstring_str(maclist[i]->name);
2367         if (i < nmacs-1)
2368             ssh2_pkt_addstring_str(",");
2369     }
2370     /* List client->server compression algorithms. */
2371     ssh2_pkt_addstring_start();
2372     for (i = 0; i < lenof(compressions)+1; i++) {
2373         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2374         ssh2_pkt_addstring_str(c->name);
2375         if (i < lenof(compressions))
2376             ssh2_pkt_addstring_str(",");
2377     }
2378     /* List server->client compression algorithms. */
2379     ssh2_pkt_addstring_start();
2380     for (i = 0; i < lenof(compressions)+1; i++) {
2381         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2382         ssh2_pkt_addstring_str(c->name);
2383         if (i < lenof(compressions))
2384             ssh2_pkt_addstring_str(",");
2385     }
2386     /* List client->server languages. Empty list. */
2387     ssh2_pkt_addstring_start();
2388     /* List server->client languages. Empty list. */
2389     ssh2_pkt_addstring_start();
2390     /* First KEX packet does _not_ follow, because we're not that brave. */
2391     ssh2_pkt_addbool(FALSE);
2392     /* Reserved. */
2393     ssh2_pkt_adduint32(0);
2394
2395     exhash = exhashbase;
2396     sha_string(&exhash, pktout.data+5, pktout.length-5);
2397
2398     ssh2_pkt_send();
2399
2400     if (!ispkt) crWaitUntil(ispkt);
2401     sha_string(&exhash, pktin.data+5, pktin.length-5);
2402
2403     /*
2404      * Now examine the other side's KEXINIT to see what we're up
2405      * to.
2406      */
2407     if (pktin.type != SSH2_MSG_KEXINIT) {
2408         bombout(("expected key exchange packet from server"));
2409         crReturn(0);
2410     }
2411     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2412     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2413     pktin.savedpos += 16;              /* skip garbage cookie */
2414     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
2415     for (i = 0; i < lenof(kex_algs); i++) {
2416         if (in_commasep_string(kex_algs[i]->name, str, len)) {
2417             kex = kex_algs[i];
2418             break;
2419         }
2420     }
2421     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
2422     for (i = 0; i < lenof(hostkey_algs); i++) {
2423         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2424             hostkey = hostkey_algs[i];
2425             break;
2426         }
2427     }
2428     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
2429     for (i = 0; i < lenof(ciphers)+1; i++) {
2430         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2431         for (j = 0; j < c->nciphers; j++) {
2432             if (in_commasep_string(c->list[j]->name, str, len)) {
2433                 cscipher_tobe = c->list[j];
2434                 break;
2435             }
2436         }
2437         if (cscipher_tobe)
2438             break;
2439     }
2440     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
2441     for (i = 0; i < lenof(ciphers)+1; i++) {
2442         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2443         for (j = 0; j < c->nciphers; j++) {
2444             if (in_commasep_string(c->list[j]->name, str, len)) {
2445                 sccipher_tobe = c->list[j];
2446                 break;
2447             }
2448         }
2449         if (sccipher_tobe)
2450             break;
2451     }
2452     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
2453     for (i = 0; i < nmacs; i++) {
2454         if (in_commasep_string(maclist[i]->name, str, len)) {
2455             csmac_tobe = maclist[i];
2456             break;
2457         }
2458     }
2459     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
2460     for (i = 0; i < nmacs; i++) {
2461         if (in_commasep_string(maclist[i]->name, str, len)) {
2462             scmac_tobe = maclist[i];
2463             break;
2464         }
2465     }
2466     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
2467     for (i = 0; i < lenof(compressions)+1; i++) {
2468         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2469         if (in_commasep_string(c->name, str, len)) {
2470             cscomp_tobe = c;
2471             break;
2472         }
2473     }
2474     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
2475     for (i = 0; i < lenof(compressions)+1; i++) {
2476         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2477         if (in_commasep_string(c->name, str, len)) {
2478             sccomp_tobe = c;
2479             break;
2480         }
2481     }
2482
2483     /*
2484      * If we're doing Diffie-Hellman group exchange, start by
2485      * requesting a group.
2486      */
2487     if (kex == &ssh_diffiehellman_gex) {
2488         int csbits, scbits;
2489
2490         logevent("Doing Diffie-Hellman group exchange");
2491         /*
2492          * Work out number of bits. We start with the maximum key
2493          * length of either cipher...
2494          */
2495         csbits = cscipher_tobe->keylen;
2496         scbits = sccipher_tobe->keylen;
2497         nbits = (csbits > scbits ? csbits : scbits);
2498         /* The keys only have 160-bit entropy, since they're based on
2499          * a SHA-1 hash. So cap the key size at 160 bits. */
2500         if (nbits > 160) nbits = 160;
2501         /*
2502          * ... and then work out how big a DH group we will need to
2503          * allow that much data.
2504          */
2505         nbits = 512 << ((nbits-1) / 64);
2506         ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2507         ssh2_pkt_adduint32(nbits);
2508         ssh2_pkt_send();
2509
2510         crWaitUntil(ispkt);
2511         if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2512             bombout(("expected key exchange group packet from server"));
2513             crReturn(0);
2514         }
2515         p = ssh2_pkt_getmp();
2516         g = ssh2_pkt_getmp();
2517         dh_setup_group(p, g);
2518         kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2519         kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2520     } else {
2521         dh_setup_group1();
2522         kex_init_value = SSH2_MSG_KEXDH_INIT;
2523         kex_reply_value = SSH2_MSG_KEXDH_REPLY;
2524     }
2525
2526     logevent("Doing Diffie-Hellman key exchange");
2527     /*
2528      * Now generate and send e for Diffie-Hellman.
2529      */
2530     e = dh_create_e();
2531     ssh2_pkt_init(kex_init_value);
2532     ssh2_pkt_addmp(e);
2533     ssh2_pkt_send();
2534
2535     crWaitUntil(ispkt);
2536     if (pktin.type != kex_reply_value) {
2537         bombout(("expected key exchange reply packet from server"));
2538         crReturn(0);
2539     }
2540     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2541     f = ssh2_pkt_getmp();
2542     ssh2_pkt_getstring(&sigdata, &siglen);
2543
2544     K = dh_find_K(f);
2545
2546     sha_string(&exhash, hostkeydata, hostkeylen);
2547     if (kex == &ssh_diffiehellman_gex) {
2548         sha_uint32(&exhash, nbits);
2549         sha_mpint(&exhash, p);
2550         sha_mpint(&exhash, g);
2551     }
2552     sha_mpint(&exhash, e);
2553     sha_mpint(&exhash, f);
2554     sha_mpint(&exhash, K);
2555     SHA_Final(&exhash, exchange_hash);
2556
2557     dh_cleanup();
2558
2559 #if 0
2560     debug(("Exchange hash is:\r\n"));
2561     for (i = 0; i < 20; i++)
2562         debug((" %02x", exchange_hash[i]));
2563     debug(("\r\n"));
2564 #endif
2565
2566     hkey = hostkey->newkey(hostkeydata, hostkeylen);
2567     if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2568         bombout(("Server failed host key check"));
2569         crReturn(0);
2570     }
2571
2572     /*
2573      * Expect SSH2_MSG_NEWKEYS from server.
2574      */
2575     crWaitUntil(ispkt);
2576     if (pktin.type != SSH2_MSG_NEWKEYS) {
2577         bombout(("expected new-keys packet from server"));
2578         crReturn(0);
2579     }
2580
2581     /*
2582      * Authenticate remote host: verify host key. (We've already
2583      * checked the signature of the exchange hash.)
2584      */
2585     keystr = hostkey->fmtkey(hkey);
2586     fingerprint = hostkey->fingerprint(hkey);
2587     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2588                         keystr, fingerprint);
2589     if (first_kex) {                /* don't bother logging this in rekeys */
2590         logevent("Host key fingerprint is:");
2591         logevent(fingerprint);
2592     }
2593     sfree(fingerprint);
2594     sfree(keystr);
2595     hostkey->freekey(hkey);
2596
2597     /*
2598      * Send SSH2_MSG_NEWKEYS.
2599      */
2600     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2601     ssh2_pkt_send();
2602
2603     /*
2604      * Create and initialise session keys.
2605      */
2606     cscipher = cscipher_tobe;
2607     sccipher = sccipher_tobe;
2608     csmac = csmac_tobe;
2609     scmac = scmac_tobe;
2610     cscomp = cscomp_tobe;
2611     sccomp = sccomp_tobe;
2612     cscomp->compress_init();
2613     sccomp->decompress_init();
2614     /*
2615      * Set IVs after keys. Here we use the exchange hash from the
2616      * _first_ key exchange.
2617      */
2618     if (first_kex)
2619         memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2620     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
2621     cscipher->setcskey(keyspace);
2622     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
2623     sccipher->setsckey(keyspace);
2624     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
2625     cscipher->setcsiv(keyspace);
2626     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
2627     sccipher->setsciv(keyspace);
2628     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
2629     csmac->setcskey(keyspace);
2630     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
2631     scmac->setsckey(keyspace);
2632
2633     /*
2634      * If this is the first key exchange phase, we must pass the
2635      * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2636      * wants to see it but because it will need time to initialise
2637      * itself before it sees an actual packet. In subsequent key
2638      * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2639      * it would only confuse the layer above.
2640      */
2641     if (!first_kex) {
2642         crReturn(0);
2643     }
2644     first_kex = 0;
2645
2646     /*
2647      * Now we're encrypting. Begin returning 1 to the protocol main
2648      * function so that other things can run on top of the
2649      * transport. If we ever see a KEXINIT, we must go back to the
2650      * start.
2651      */
2652     while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2653         crReturn(1);
2654     }
2655     logevent("Server initiated key re-exchange");
2656     goto begin_key_exchange;
2657
2658     crFinish(1);
2659 }
2660
2661 /*
2662  * Add data to an SSH2 channel output buffer.
2663  */
2664 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2665     if (c->v2.outbufsize <
2666         c->v2.outbuflen + len) {
2667         c->v2.outbufsize =
2668             c->v2.outbuflen + len + 1024;
2669         c->v2.outbuffer = srealloc(c->v2.outbuffer,
2670                                    c->v2.outbufsize);
2671     }
2672     memcpy(c->v2.outbuffer + c->v2.outbuflen,
2673            buf, len);
2674     c->v2.outbuflen += len;
2675 }
2676
2677 /*
2678  * Attempt to send data on an SSH2 channel.
2679  */
2680 static void ssh2_try_send(struct ssh_channel *c) {
2681     while (c->v2.remwindow > 0 &&
2682            c->v2.outbuflen > 0) {
2683         unsigned len = c->v2.remwindow;
2684         if (len > c->v2.outbuflen)
2685             len = c->v2.outbuflen;
2686         if (len > c->v2.remmaxpkt)
2687             len = c->v2.remmaxpkt;
2688         ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2689         ssh2_pkt_adduint32(c->remoteid);
2690         ssh2_pkt_addstring_start();
2691         ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2692         ssh2_pkt_send();
2693         c->v2.outbuflen -= len;
2694         memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2695                 c->v2.outbuflen);
2696         c->v2.remwindow -= len;
2697     }
2698 }
2699
2700 /*
2701  * Handle the SSH2 userauth and connection layers.
2702  */
2703 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2704 {
2705     static unsigned long remote_winsize;
2706     static unsigned long remote_maxpkt;
2707     static enum {
2708         AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2709     } method;
2710     static enum {
2711         AUTH_TYPE_NONE,
2712         AUTH_TYPE_PUBLICKEY,
2713         AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2714         AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2715         AUTH_TYPE_PASSWORD
2716     } type;
2717     static int gotit, need_pw, can_pubkey, can_passwd;
2718     static int tried_pubkey_config, tried_agent;
2719     static int we_are_in;
2720     static char username[100];
2721     static char pwprompt[200];
2722     static char password[100];
2723
2724     crBegin;
2725
2726     /*
2727      * Request userauth protocol, and await a response to it.
2728      */
2729     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2730     ssh2_pkt_addstring("ssh-userauth");
2731     ssh2_pkt_send();
2732     crWaitUntilV(ispkt);
2733     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2734         bombout(("Server refused user authentication protocol"));
2735         crReturnV;
2736     }
2737
2738     /*
2739      * We repeat this whole loop, including the username prompt,
2740      * until we manage a successful authentication. If the user
2741      * types the wrong _password_, they are sent back to the
2742      * beginning to try another username. (If they specify a
2743      * username in the config, they are never asked, even if they
2744      * do give a wrong password.)
2745      * 
2746      * I think this best serves the needs of
2747      * 
2748      *  - the people who have no configuration, no keys, and just
2749      *    want to try repeated (username,password) pairs until they
2750      *    type both correctly
2751      * 
2752      *  - people who have keys and configuration but occasionally
2753      *    need to fall back to passwords
2754      * 
2755      *  - people with a key held in Pageant, who might not have
2756      *    logged in to a particular machine before; so they want to
2757      *    type a username, and then _either_ their key will be
2758      *    accepted, _or_ they will type a password. If they mistype
2759      *    the username they will want to be able to get back and
2760      *    retype it!
2761      */
2762     do {
2763         static int pos;
2764         static char c;
2765
2766         /*
2767          * Get a username.
2768          */
2769         pos = 0;
2770         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2771             c_write_str("login as: ");
2772             ssh_send_ok = 1;
2773             while (pos >= 0) {
2774                 crWaitUntilV(!ispkt);
2775                 while (inlen--) switch (c = *in++) {
2776                   case 10: case 13:
2777                     username[pos] = 0;
2778                     pos = -1;
2779                     break;
2780                   case 8: case 127:
2781                     if (pos > 0) {
2782                         c_write_str("\b \b");
2783                         pos--;
2784                     }
2785                     break;
2786                   case 21: case 27:
2787                     while (pos > 0) {
2788                         c_write_str("\b \b");
2789                         pos--;
2790                     }
2791                     break;
2792                   case 3: case 4:
2793                     random_save_seed();
2794                     exit(0);
2795                     break;
2796                   default:
2797                     if (((c >= ' ' && c <= '~') ||
2798                          ((unsigned char)c >= 160)) && pos < 40) {
2799                         username[pos++] = c;
2800                         c_write(&c, 1);
2801                     }
2802                     break;
2803                 }
2804             }
2805             c_write_str("\r\n");
2806             username[strcspn(username, "\n\r")] = '\0';
2807         } else {
2808             char stuff[200];
2809             strncpy(username, cfg.username, 99);
2810             username[99] = '\0';
2811             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2812                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2813                 c_write_str(stuff);
2814             }
2815         }
2816
2817         /*
2818          * Send an authentication request using method "none": (a)
2819          * just in case it succeeds, and (b) so that we know what
2820          * authentication methods we can usefully try next.
2821          */
2822         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2823         ssh2_pkt_addstring(username);
2824         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2825         ssh2_pkt_addstring("none");    /* method */
2826         ssh2_pkt_send();
2827         type = AUTH_TYPE_NONE;
2828         gotit = FALSE;
2829         we_are_in = FALSE;
2830
2831         tried_pubkey_config = FALSE;
2832         tried_agent = FALSE;
2833
2834         while (1) {
2835             /*
2836              * Wait for the result of the last authentication request.
2837              */
2838             if (!gotit)
2839                 crWaitUntilV(ispkt);
2840             while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2841                 /* FIXME: should support this */
2842                 crWaitUntilV(ispkt);
2843             }
2844             if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2845                 logevent("Access granted");
2846                 we_are_in = TRUE;
2847                 break;
2848             }
2849
2850             if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2851                 bombout(("Strange packet received during authentication: type %d",
2852                          pktin.type));
2853             }
2854
2855             gotit = FALSE;
2856
2857             /*
2858              * OK, we're now sitting on a USERAUTH_FAILURE message, so
2859              * we can look at the string in it and know what we can
2860              * helpfully try next.
2861              */
2862             {
2863                 char *methods;
2864                 int methlen;
2865                 ssh2_pkt_getstring(&methods, &methlen);
2866                 if (!ssh2_pkt_getbool()) {
2867                     /*
2868                      * We have received an unequivocal Access
2869                      * Denied. This can translate to a variety of
2870                      * messages:
2871                      * 
2872                      *  - if we'd just tried "none" authentication,
2873                      *    it's not worth printing anything at all
2874                      * 
2875                      *  - if we'd just tried a public key _offer_,
2876                      *    the message should be "Server refused our
2877                      *    key" (or no message at all if the key
2878                      *    came from Pageant)
2879                      * 
2880                      *  - if we'd just tried anything else, the
2881                      *    message really should be "Access denied".
2882                      * 
2883                      * Additionally, if we'd just tried password
2884                      * authentication, we should break out of this
2885                      * whole loop so as to go back to the username
2886                      * prompt.
2887                      */
2888                     if (type == AUTH_TYPE_NONE) {
2889                         /* do nothing */
2890                     } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2891                                type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2892                         if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2893                             c_write_str("Server refused our key\r\n");
2894                         logevent("Server refused public key");
2895                     } else {
2896                         c_write_str("Access denied\r\n");
2897                         logevent("Access denied");
2898                         if (type == AUTH_TYPE_PASSWORD) {
2899                             we_are_in = FALSE;
2900                             break;
2901                         }
2902                     }
2903                 } else {
2904                     c_write_str("Further authentication required\r\n");
2905                     logevent("Further authentication required");
2906                 }
2907
2908                 can_pubkey = in_commasep_string("publickey", methods, methlen);
2909                 can_passwd = in_commasep_string("password", methods, methlen);
2910             }
2911
2912             method = 0;
2913
2914             if (!method && can_pubkey && agent_exists && !tried_agent) {
2915                 /*
2916                  * Attempt public-key authentication using Pageant.
2917                  */
2918                 static unsigned char request[5], *response, *p;
2919                 static int responselen;
2920                 static int i, nkeys;
2921                 static int authed = FALSE;
2922                 void *r;
2923
2924                 tried_agent = TRUE;
2925
2926                 logevent("Pageant is running. Requesting keys.");
2927
2928                 /* Request the keys held by the agent. */
2929                 PUT_32BIT(request, 1);
2930                 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
2931                 agent_query(request, 5, &r, &responselen);
2932                 response = (unsigned char *)r;
2933                 if (response) {
2934                     p = response + 5;
2935                     nkeys = GET_32BIT(p); p += 4;
2936                     { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
2937                         logevent(buf); }
2938                     for (i = 0; i < nkeys; i++) {
2939                         static char *pkblob, *alg, *commentp;
2940                         static int pklen, alglen, commentlen;
2941                         static int siglen, retlen, len;
2942                         static char *q, *agentreq, *ret;
2943
2944                         { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
2945                             logevent(buf); }
2946                         pklen = GET_32BIT(p); p += 4;
2947                         pkblob = p; p += pklen;
2948                         alglen = GET_32BIT(pkblob);
2949                         alg = pkblob + 4;
2950                         commentlen = GET_32BIT(p); p += 4;
2951                         commentp = p; p += commentlen;
2952                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2953                         ssh2_pkt_addstring(username);
2954                         ssh2_pkt_addstring("ssh-connection");/* service requested */
2955                         ssh2_pkt_addstring("publickey");/* method */
2956                         ssh2_pkt_addbool(FALSE);   /* no signature included */
2957                         ssh2_pkt_addstring_start();
2958                         ssh2_pkt_addstring_data(alg, alglen);
2959                         ssh2_pkt_addstring_start();
2960                         ssh2_pkt_addstring_data(pkblob, pklen);
2961                         ssh2_pkt_send();
2962
2963                         crWaitUntilV(ispkt);
2964                         if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
2965                             logevent("Key refused");
2966                             continue;
2967                         }
2968
2969                         c_write_str("Authenticating with public key \"");
2970                         c_write(commentp, commentlen);
2971                         c_write_str("\" from agent\r\n");
2972
2973                         /*
2974                          * Server is willing to accept the key.
2975                          * Construct a SIGN_REQUEST.
2976                          */
2977                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2978                         ssh2_pkt_addstring(username);
2979                         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2980                         ssh2_pkt_addstring("publickey");    /* method */
2981                         ssh2_pkt_addbool(TRUE);
2982                         ssh2_pkt_addstring_start();
2983                         ssh2_pkt_addstring_data(alg, alglen);
2984                         ssh2_pkt_addstring_start();
2985                         ssh2_pkt_addstring_data(pkblob, pklen);
2986
2987                         siglen = pktout.length - 5 + 4 + 20;
2988                         len = 1;   /* message type */
2989                         len += 4 + pklen;   /* key blob */
2990                         len += 4 + siglen;   /* data to sign */
2991                         len += 4;  /* flags */
2992                         agentreq = smalloc(4 + len);
2993                         PUT_32BIT(agentreq, len);
2994                         q = agentreq + 4;
2995                         *q++ = SSH2_AGENTC_SIGN_REQUEST;
2996                         PUT_32BIT(q, pklen); q += 4;
2997                         memcpy(q, pkblob, pklen); q += pklen;
2998                         PUT_32BIT(q, siglen); q += 4;
2999                         /* Now the data to be signed... */
3000                         PUT_32BIT(q, 20); q += 4;
3001                         memcpy(q, ssh2_session_id, 20); q += 20;
3002                         memcpy(q, pktout.data+5, pktout.length-5);
3003                         q += pktout.length-5;
3004                         /* And finally the (zero) flags word. */
3005                         PUT_32BIT(q, 0);
3006                         agent_query(agentreq, len+4, &ret, &retlen);
3007                         sfree(agentreq);
3008                         if (ret) {
3009                             if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3010                                 logevent("Sending Pageant's response");
3011                                 ssh2_pkt_addstring_start();
3012                                 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3013                                 ssh2_pkt_send();
3014                                 authed = TRUE;
3015                                 break;
3016                             } else {
3017                                 logevent("Pageant failed to answer challenge");
3018                                 sfree(ret);
3019                             }
3020                         }
3021                     }
3022                     if (authed)
3023                         continue;
3024                 }
3025             }
3026
3027             if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3028                 unsigned char *pub_blob;
3029                 char *algorithm, *comment;
3030                 int pub_blob_len;
3031
3032                 tried_pubkey_config = TRUE;
3033
3034                 /*
3035                  * Try the public key supplied in the configuration.
3036                  *
3037                  * First, offer the public blob to see if the server is
3038                  * willing to accept it.
3039                  */
3040                 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3041                                                 &pub_blob_len);
3042                 if (pub_blob) {
3043                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3044                     ssh2_pkt_addstring(username);
3045                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3046                     ssh2_pkt_addstring("publickey");/* method */
3047                     ssh2_pkt_addbool(FALSE);   /* no signature included */
3048                     ssh2_pkt_addstring(algorithm);
3049                     ssh2_pkt_addstring_start();
3050                     ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3051                     ssh2_pkt_send();
3052                     logevent("Offered public key"); /* FIXME */
3053
3054                     crWaitUntilV(ispkt);
3055                     if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3056                         gotit = TRUE;
3057                         type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3058                         continue;              /* key refused; give up on it */
3059                     }
3060
3061                     logevent("Offer of public key accepted");
3062                     /*
3063                      * Actually attempt a serious authentication using
3064                      * the key.
3065                      */
3066                     if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3067                         sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3068                         need_pw = TRUE;
3069                     } else {
3070                         need_pw = FALSE;
3071                     }
3072                     c_write_str("Authenticating with public key \"");
3073                     c_write_str(comment);
3074                     c_write_str("\"\r\n");
3075                     method = AUTH_PUBLICKEY_FILE;
3076                 }
3077             }
3078
3079             if (!method && can_passwd) {
3080                 method = AUTH_PASSWORD;
3081                 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3082                 need_pw = TRUE;
3083             }
3084
3085             if (need_pw) {
3086                 if (ssh_get_password) {
3087                     if (!ssh_get_password(pwprompt, password, sizeof(password))) {
3088                         /*
3089                          * get_password failed to get a password (for
3090                          * example because one was supplied on the command
3091                          * line which has already failed to work).
3092                          * Terminate.
3093                          */
3094                         logevent("No more passwords to try");
3095                         ssh_state = SSH_STATE_CLOSED;
3096                         crReturnV;
3097                     }
3098                 } else {
3099                     static int pos = 0;
3100                     static char c;
3101
3102                     c_write_str(pwprompt);
3103                     ssh_send_ok = 1;
3104
3105                     pos = 0;
3106                     while (pos >= 0) {
3107                         crWaitUntilV(!ispkt);
3108                         while (inlen--) switch (c = *in++) {
3109                           case 10: case 13:
3110                             password[pos] = 0;
3111                             pos = -1;
3112                             break;
3113                           case 8: case 127:
3114                             if (pos > 0)
3115                                 pos--;
3116                             break;
3117                           case 21: case 27:
3118                             pos = 0;
3119                             break;
3120                           case 3: case 4:
3121                             random_save_seed();
3122                             exit(0);
3123                             break;
3124                           default:
3125                             if (((c >= ' ' && c <= '~') ||
3126                                  ((unsigned char)c >= 160)) && pos < 40)
3127                                 password[pos++] = c;
3128                             break;
3129                         }
3130                     }
3131                     c_write_str("\r\n");
3132                 }
3133             }
3134
3135             if (method == AUTH_PUBLICKEY_FILE) {
3136                 /*
3137                  * We have our passphrase. Now try the actual authentication.
3138                  */
3139                 struct ssh2_userkey *key;
3140
3141                 key = ssh2_load_userkey(cfg.keyfile, password);
3142                 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3143                     if (key == SSH2_WRONG_PASSPHRASE) {
3144                         c_write_str("Wrong passphrase\r\n");
3145                         tried_pubkey_config = FALSE;
3146                     } else {
3147                         c_write_str("Unable to load private key\r\n");
3148                         tried_pubkey_config = TRUE;
3149                     }
3150                     /* Send a spurious AUTH_NONE to return to the top. */
3151                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3152                     ssh2_pkt_addstring(username);
3153                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3154                     ssh2_pkt_addstring("none");    /* method */
3155                     ssh2_pkt_send();
3156                     type = AUTH_TYPE_NONE;
3157                 } else {
3158                     unsigned char *blob, *sigdata;
3159                     int blob_len, sigdata_len;
3160
3161                     /*
3162                      * We have loaded the private key and the server
3163                      * has announced that it's willing to accept it.
3164                      * Hallelujah. Generate a signature and send it.
3165                      */
3166                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3167                     ssh2_pkt_addstring(username);
3168                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3169                     ssh2_pkt_addstring("publickey");    /* method */
3170                     ssh2_pkt_addbool(TRUE);
3171                     ssh2_pkt_addstring(key->alg->name);
3172                     blob = key->alg->public_blob(key->data, &blob_len);
3173                     ssh2_pkt_addstring_start();
3174                     ssh2_pkt_addstring_data(blob, blob_len);
3175                     sfree(blob);
3176
3177                     /*
3178                      * The data to be signed is:
3179                      *
3180                      *   string  session-id
3181                      *
3182                      * followed by everything so far placed in the
3183                      * outgoing packet.
3184                      */
3185                     sigdata_len = pktout.length - 5 + 4 + 20;
3186                     sigdata = smalloc(sigdata_len);
3187                     PUT_32BIT(sigdata, 20);
3188                     memcpy(sigdata+4, ssh2_session_id, 20);
3189                     memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3190                     blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3191                     ssh2_pkt_addstring_start();
3192                     ssh2_pkt_addstring_data(blob, blob_len);
3193                     sfree(blob);
3194                     sfree(sigdata);
3195
3196                     ssh2_pkt_send();
3197                     type = AUTH_TYPE_PUBLICKEY;
3198                 }
3199             } else if (method == AUTH_PASSWORD) {
3200                 /*
3201                  * We send the password packet lumped tightly together with
3202                  * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3203                  * string long enough to make the total length of the two
3204                  * packets constant. This should ensure that a passive
3205                  * listener doing traffic analyis can't work out the length
3206                  * of the password.
3207                  *
3208                  * For this to work, we need an assumption about the
3209                  * maximum length of the password packet. I think 256 is
3210                  * pretty conservative. Anyone using a password longer than
3211                  * that probably doesn't have much to worry about from
3212                  * people who find out how long their password is!
3213                  */
3214                 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3215                 ssh2_pkt_addstring(username);
3216                 ssh2_pkt_addstring("ssh-connection");   /* service requested */
3217                 ssh2_pkt_addstring("password");
3218                 ssh2_pkt_addbool(FALSE);
3219                 ssh2_pkt_addstring(password);
3220                 ssh2_pkt_defer();
3221                 /*
3222                  * We'll include a string that's an exact multiple of the
3223                  * cipher block size. If the cipher is NULL for some
3224                  * reason, we don't do this trick at all because we gain
3225                  * nothing by it.
3226                  */
3227                 if (cscipher) {
3228                     int stringlen, i;
3229
3230                     stringlen = (256 - deferred_len);
3231                     stringlen += cscipher->blksize - 1;
3232                     stringlen -= (stringlen % cscipher->blksize);
3233                     if (cscomp) {
3234                         /*
3235                          * Temporarily disable actual compression,
3236                          * so we can guarantee to get this string
3237                          * exactly the length we want it. The
3238                          * compression-disabling routine should
3239                          * return an integer indicating how many
3240                          * bytes we should adjust our string length
3241                          * by.
3242                          */
3243                         stringlen -= cscomp->disable_compression();
3244                     }
3245                     ssh2_pkt_init(SSH2_MSG_IGNORE);
3246                     ssh2_pkt_addstring_start();
3247                     for (i = 0; i < stringlen; i++) {
3248                         char c = (char)random_byte();
3249                         ssh2_pkt_addstring_data(&c, 1);
3250                     }
3251                     ssh2_pkt_defer();
3252                 }
3253                 ssh_pkt_defersend();
3254                 logevent("Sent password");
3255                 type = AUTH_TYPE_PASSWORD;
3256             } else {
3257                 c_write_str("No supported authentication methods left to try!\r\n");
3258                 logevent("No supported authentications offered. Disconnecting");
3259                 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3260                 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3261                 ssh2_pkt_addstring("No supported authentication methods available");
3262                 ssh2_pkt_addstring("en");   /* language tag */
3263                 ssh2_pkt_send();
3264                 ssh_state = SSH_STATE_CLOSED;
3265                 crReturnV;
3266             }
3267         }
3268     } while (!we_are_in);
3269
3270     /*
3271      * Now we're authenticated for the connection protocol. The
3272      * connection protocol will automatically have started at this
3273      * point; there's no need to send SERVICE_REQUEST.
3274      */
3275
3276     /*
3277      * So now create a channel with a session in it.
3278      */
3279     mainchan = smalloc(sizeof(struct ssh_channel));
3280     mainchan->localid = 100;           /* as good as any */
3281     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3282     ssh2_pkt_addstring("session");
3283     ssh2_pkt_adduint32(mainchan->localid);
3284     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
3285     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
3286     ssh2_pkt_send();
3287     crWaitUntilV(ispkt);
3288     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
3289         bombout(("Server refused to open a session"));
3290         crReturnV;
3291         /* FIXME: error data comes back in FAILURE packet */
3292     }
3293     if (ssh2_pkt_getuint32() != mainchan->localid) {
3294         bombout(("Server's channel confirmation cited wrong channel"));
3295         crReturnV;
3296     }
3297     mainchan->remoteid = ssh2_pkt_getuint32();
3298     mainchan->type = CHAN_MAINSESSION;
3299     mainchan->closes = 0;
3300     mainchan->v2.remwindow = ssh2_pkt_getuint32();
3301     mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3302     mainchan->v2.outbuffer = NULL;
3303     mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3304     ssh_channels = newtree234(ssh_channelcmp);
3305     add234(ssh_channels, mainchan);
3306     logevent("Opened channel for session");
3307
3308     /*
3309      * Potentially enable X11 forwarding.
3310      */
3311     if (cfg.x11_forward) {
3312         char proto[20], data[64];
3313         logevent("Requesting X11 forwarding");
3314         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3315         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3316         ssh2_pkt_adduint32(mainchan->remoteid);
3317         ssh2_pkt_addstring("x11-req");
3318         ssh2_pkt_addbool(1);           /* want reply */
3319         ssh2_pkt_addbool(0);           /* many connections */
3320         ssh2_pkt_addstring(proto);
3321         ssh2_pkt_addstring(data);
3322         ssh2_pkt_adduint32(0);         /* screen number */
3323         ssh2_pkt_send();
3324
3325         do {
3326             crWaitUntilV(ispkt);
3327             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3328                 unsigned i = ssh2_pkt_getuint32();
3329                 struct ssh_channel *c;
3330                 c = find234(ssh_channels, &i, ssh_channelfind);
3331                 if (!c)
3332                     continue;          /* nonexistent channel */
3333                 c->v2.remwindow += ssh2_pkt_getuint32();
3334             }
3335         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3336
3337         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3338             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3339                 bombout(("Server got confused by X11 forwarding request"));
3340                 crReturnV;
3341             }
3342             logevent("X11 forwarding refused");
3343         } else {
3344             logevent("X11 forwarding enabled");
3345             ssh_X11_fwd_enabled = TRUE;
3346         }
3347     }
3348
3349     /*
3350      * Potentially enable agent forwarding.
3351      */
3352     if (cfg.agentfwd && agent_exists()) {
3353         char proto[20], data[64];
3354         logevent("Requesting OpenSSH-style agent forwarding");
3355         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3356         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3357         ssh2_pkt_adduint32(mainchan->remoteid);
3358         ssh2_pkt_addstring("auth-agent-req@openssh.com");
3359         ssh2_pkt_addbool(1);           /* want reply */
3360         ssh2_pkt_send();
3361
3362         do {
3363             crWaitUntilV(ispkt);
3364             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3365                 unsigned i = ssh2_pkt_getuint32();
3366                 struct ssh_channel *c;
3367                 c = find234(ssh_channels, &i, ssh_channelfind);
3368                 if (!c)
3369                     continue;          /* nonexistent channel */
3370                 c->v2.remwindow += ssh2_pkt_getuint32();
3371             }
3372         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3373
3374         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3375             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3376                 bombout(("Server got confused by agent forwarding request"));
3377                 crReturnV;
3378             }
3379             logevent("Agent forwarding refused");
3380         } else {
3381             logevent("Agent forwarding enabled");
3382             ssh_agentfwd_enabled = TRUE;
3383         }
3384     }
3385
3386     /*
3387      * Now allocate a pty for the session.
3388      */
3389     if (!cfg.nopty) {
3390         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3391         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3392         ssh2_pkt_addstring("pty-req");
3393         ssh2_pkt_addbool(1);           /* want reply */
3394         ssh2_pkt_addstring(cfg.termtype);
3395         ssh2_pkt_adduint32(cols);
3396         ssh2_pkt_adduint32(rows);
3397         ssh2_pkt_adduint32(0);         /* pixel width */
3398         ssh2_pkt_adduint32(0);         /* pixel height */
3399         ssh2_pkt_addstring_start();
3400         ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3401         ssh2_pkt_send();
3402         ssh_state = SSH_STATE_INTERMED;
3403
3404         do {
3405             crWaitUntilV(ispkt);
3406             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3407                 unsigned i = ssh2_pkt_getuint32();
3408                 struct ssh_channel *c;
3409                 c = find234(ssh_channels, &i, ssh_channelfind);
3410                 if (!c)
3411                     continue;          /* nonexistent channel */
3412                 c->v2.remwindow += ssh2_pkt_getuint32();
3413             }
3414         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3415
3416         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3417             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3418                 bombout(("Server got confused by pty request"));
3419                 crReturnV;
3420             }
3421             c_write_str("Server refused to allocate pty\r\n");
3422             ssh_editing = ssh_echoing = 1;
3423         } else {
3424             logevent("Allocated pty");
3425         }
3426     } else {
3427         ssh_editing = ssh_echoing = 1;
3428     }
3429
3430     /*
3431      * Start a shell or a remote command.
3432      */
3433     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3434     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3435     if (cfg.ssh_subsys) {
3436         ssh2_pkt_addstring("subsystem");
3437         ssh2_pkt_addbool(1);           /* want reply */
3438         ssh2_pkt_addstring(cfg.remote_cmd);
3439     } else if (*cfg.remote_cmd) {
3440         ssh2_pkt_addstring("exec");
3441         ssh2_pkt_addbool(1);           /* want reply */
3442         ssh2_pkt_addstring(cfg.remote_cmd);
3443     } else {
3444         ssh2_pkt_addstring("shell");
3445         ssh2_pkt_addbool(1);           /* want reply */
3446     }
3447     ssh2_pkt_send();
3448     do {
3449         crWaitUntilV(ispkt);
3450         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3451             unsigned i = ssh2_pkt_getuint32();
3452             struct ssh_channel *c;
3453             c = find234(ssh_channels, &i, ssh_channelfind);
3454             if (!c)
3455                 continue;              /* nonexistent channel */
3456             c->v2.remwindow += ssh2_pkt_getuint32();
3457         }
3458     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3459     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3460         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3461             bombout(("Server got confused by shell/command request"));
3462             crReturnV;
3463         }
3464         bombout(("Server refused to start a shell/command"));
3465         crReturnV;
3466     } else {
3467         logevent("Started a shell/command");
3468     }
3469
3470     ssh_state = SSH_STATE_SESSION;
3471     if (size_needed)
3472         ssh_size();
3473     if (eof_needed)
3474         ssh_special(TS_EOF);
3475
3476     /*
3477      * Transfer data!
3478      */
3479     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
3480     ssh_send_ok = 1;
3481     while (1) {
3482         static int try_send;
3483         crReturnV;
3484         try_send = FALSE;
3485         if (ispkt) {
3486             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3487                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3488                 char *data;
3489                 int length;
3490                 unsigned i = ssh2_pkt_getuint32();
3491                 struct ssh_channel *c;
3492                 c = find234(ssh_channels, &i, ssh_channelfind);
3493                 if (!c)
3494                     continue;          /* nonexistent channel */
3495                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3496                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3497                     continue;          /* extended but not stderr */
3498                 ssh2_pkt_getstring(&data, &length);
3499                 if (data) {
3500                     switch (c->type) {
3501                       case CHAN_MAINSESSION:
3502                         from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3503                                      data, length);
3504                         break;
3505                       case CHAN_X11:
3506                         x11_send(c->u.x11.s, data, length);
3507                         break;
3508                       case CHAN_AGENT:
3509                         while (length > 0) {
3510                             if (c->u.a.lensofar < 4) {
3511                                 int l = min(4 - c->u.a.lensofar, length);
3512                                 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3513                                 data += l; length -= l; c->u.a.lensofar += l;
3514                             }
3515                             if (c->u.a.lensofar == 4) {
3516                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3517                                 c->u.a.message = smalloc(c->u.a.totallen);
3518                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
3519                             }
3520                             if (c->u.a.lensofar >= 4 && length > 0) {
3521                                 int l = min(c->u.a.totallen - c->u.a.lensofar,
3522                                             length);
3523                                 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3524                                 data += l; length -= l; c->u.a.lensofar += l;
3525                             }
3526                             if (c->u.a.lensofar == c->u.a.totallen) {
3527                                 void *reply, *sentreply;
3528                                 int replylen;
3529                                 agent_query(c->u.a.message, c->u.a.totallen,
3530                                             &reply, &replylen);
3531                                 if (reply)
3532                                     sentreply = reply;
3533                                 else {
3534                                     /* Fake SSH_AGENT_FAILURE. */
3535                                     sentreply = "\0\0\0\1\5";
3536                                     replylen = 5;
3537                                 }
3538                                 ssh2_add_channel_data(c, sentreply, replylen);
3539                                 try_send = TRUE;
3540                                 if (reply)
3541                                     sfree(reply);
3542                                 sfree(c->u.a.message);
3543                                 c->u.a.lensofar = 0;
3544                             }
3545                         }
3546                         break;
3547                     }
3548                     /*
3549                      * Enlarge the window again at the remote
3550                      * side, just in case it ever runs down and
3551                      * they fail to send us any more data.
3552                      */
3553                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3554                     ssh2_pkt_adduint32(c->remoteid);
3555                     ssh2_pkt_adduint32(length);
3556                     ssh2_pkt_send();
3557                 }
3558             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3559                 ssh_state = SSH_STATE_CLOSED;
3560                 logevent("Received disconnect message");
3561                 crReturnV;
3562             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3563                 continue;              /* exit status et al; ignore (FIXME?) */
3564             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
3565                 unsigned i = ssh2_pkt_getuint32();
3566                 struct ssh_channel *c;
3567
3568                 c = find234(ssh_channels, &i, ssh_channelfind);
3569                 if (!c)
3570                     continue;          /* nonexistent channel */
3571                 
3572                 if (c->type == CHAN_X11) {
3573                     /*
3574                      * Remote EOF on an X11 channel means we should
3575                      * wrap up and close the channel ourselves.
3576                      */
3577                     x11_close(c->u.x11.s);
3578                     sshfwd_close(c);
3579                 } else if (c->type == CHAN_AGENT) {
3580                     sshfwd_close(c);
3581                 }
3582             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
3583                 unsigned i = ssh2_pkt_getuint32();
3584                 struct ssh_channel *c;
3585                 enum234 e;
3586
3587                 c = find234(ssh_channels, &i, ssh_channelfind);
3588                 if (!c)
3589                     continue;          /* nonexistent channel */
3590                 if (c->closes == 0) {
3591                     ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3592                     ssh2_pkt_adduint32(c->remoteid);
3593                     ssh2_pkt_send();
3594                 }
3595                 /* Do pre-close processing on the channel. */
3596                 switch (c->type) {
3597                   case CHAN_MAINSESSION:
3598                     break;             /* nothing to see here, move along */
3599                   case CHAN_X11:
3600                     break;
3601                   case CHAN_AGENT:
3602                     break;
3603                 }
3604                 del234(ssh_channels, c);
3605                 sfree(c->v2.outbuffer);
3606                 sfree(c);
3607
3608                 /*
3609                  * See if that was the last channel left open.
3610                  */
3611                 c = first234(ssh_channels, &e);
3612                 if (!c) {
3613                     logevent("All channels closed. Disconnecting");
3614                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3615                     ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3616                     ssh2_pkt_addstring("All open channels closed");
3617                     ssh2_pkt_addstring("en");   /* language tag */
3618                     ssh2_pkt_send();
3619                     ssh_state = SSH_STATE_CLOSED;
3620                     crReturnV;
3621                 }
3622                 continue;              /* remote sends close; ignore (FIXME) */
3623             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3624                 unsigned i = ssh2_pkt_getuint32();
3625                 struct ssh_channel *c;
3626                 c = find234(ssh_channels, &i, ssh_channelfind);
3627                 if (!c)
3628                     continue;          /* nonexistent channel */
3629                 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3630                 try_send = TRUE;
3631             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3632                 char *type;
3633                 int typelen;
3634                 char *error = NULL;
3635                 struct ssh_channel *c;
3636                 ssh2_pkt_getstring(&type, &typelen);
3637                 c = smalloc(sizeof(struct ssh_channel));
3638
3639                 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3640                     if (!ssh_X11_fwd_enabled)
3641                         error = "X11 forwarding is not enabled";
3642                     else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3643                         error = "Unable to open an X11 connection";
3644                     } else {
3645                         c->type = CHAN_X11;
3646                     }
3647                 } else if (typelen == 22 &&
3648                            !memcmp(type, "auth-agent@openssh.com", 3)) {
3649                     if (!ssh_agentfwd_enabled)
3650                         error = "Agent forwarding is not enabled";
3651                     else {
3652                         c->type = CHAN_AGENT;   /* identify channel type */
3653                         c->u.a.lensofar = 0;
3654                     }
3655                 } else {
3656                     error = "Unsupported channel type requested";
3657                 }
3658
3659                 c->remoteid = ssh2_pkt_getuint32();
3660                 if (error) {
3661                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3662                     ssh2_pkt_adduint32(c->remoteid);
3663                     ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3664                     ssh2_pkt_addstring(error);
3665                     ssh2_pkt_addstring("en");   /* language tag */
3666                     ssh2_pkt_send();
3667                     sfree(c);
3668                 } else {
3669                     struct ssh_channel *d;
3670                     unsigned i;
3671                     enum234 e;
3672
3673                     for (i=1, d = first234(ssh_channels, &e); d;
3674                          d = next234(&e)) {
3675                         if (d->localid > i)
3676                             break;     /* found a free number */
3677                         i = d->localid + 1;
3678                     }
3679                     c->localid = i;
3680                     c->closes = 0;
3681                     c->v2.remwindow = ssh2_pkt_getuint32();
3682                     c->v2.remmaxpkt = ssh2_pkt_getuint32();
3683                     c->v2.outbuffer = NULL;
3684                     c->v2.outbuflen = c->v2.outbufsize = 0;
3685                     add234(ssh_channels, c);
3686                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3687                     ssh2_pkt_adduint32(c->remoteid);
3688                     ssh2_pkt_adduint32(c->localid);
3689                     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
3690                     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
3691                     ssh2_pkt_send();
3692                 }
3693             } else {
3694                 bombout(("Strange packet received: type %d", pktin.type));
3695                 crReturnV;
3696             }
3697         } else {
3698             /*
3699              * We have spare data. Add it to the channel buffer.
3700              */
3701             ssh2_add_channel_data(mainchan, in, inlen);
3702             try_send = TRUE;
3703         }
3704         if (try_send) {
3705             enum234 e;
3706             struct ssh_channel *c;
3707             /*
3708              * Try to send data on all channels if we can.
3709              */
3710             for (c = first234(ssh_channels, &e); c; c = next234(&e))
3711                 ssh2_try_send(c);
3712         }
3713     }
3714
3715     crFinishV;
3716 }
3717
3718 /*
3719  * Handle the top-level SSH2 protocol.
3720  */
3721 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3722 {
3723     if (do_ssh2_transport(in, inlen, ispkt) == 0)
3724         return;
3725     do_ssh2_authconn(in, inlen, ispkt);
3726 }
3727
3728 /*
3729  * Called to set up the connection.
3730  *
3731  * Returns an error message, or NULL on success.
3732  */
3733 static char *ssh_init (char *host, int port, char **realhost) {
3734     char *p;
3735         
3736 #ifdef MSCRYPTOAPI
3737     if(crypto_startup() == 0)
3738         return "Microsoft high encryption pack not installed!";
3739 #endif
3740
3741     ssh_send_ok = 0;
3742     ssh_editing = 0;
3743     ssh_echoing = 0;
3744
3745     p = connect_to_host(host, port, realhost);
3746     if (p != NULL)
3747         return p;
3748
3749     return NULL;
3750 }
3751
3752 /*
3753  * Called to send data down the Telnet connection.
3754  */
3755 static void ssh_send (char *buf, int len) {
3756     if (s == NULL || ssh_protocol == NULL)
3757         return;
3758
3759     ssh_protocol(buf, len, 0);
3760 }
3761
3762 /*
3763  * Called to set the size of the window from SSH's POV.
3764  */
3765 static void ssh_size(void) {
3766     switch (ssh_state) {
3767       case SSH_STATE_BEFORE_SIZE:
3768       case SSH_STATE_PREPACKET:
3769       case SSH_STATE_CLOSED:
3770         break;                         /* do nothing */
3771       case SSH_STATE_INTERMED:
3772         size_needed = TRUE;            /* buffer for later */
3773         break;
3774       case SSH_STATE_SESSION:
3775         if (!cfg.nopty) {
3776             if (ssh_version == 1) {
3777                 send_packet(SSH1_CMSG_WINDOW_SIZE,
3778                             PKT_INT, rows, PKT_INT, cols,
3779                             PKT_INT, 0, PKT_INT, 0, PKT_END);
3780             } else {
3781                 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3782                 ssh2_pkt_adduint32(mainchan->remoteid);
3783                 ssh2_pkt_addstring("window-change");
3784                 ssh2_pkt_addbool(0);
3785                 ssh2_pkt_adduint32(cols);
3786                 ssh2_pkt_adduint32(rows);
3787                 ssh2_pkt_adduint32(0);
3788                 ssh2_pkt_adduint32(0);
3789                 ssh2_pkt_send();
3790             }
3791         }
3792         break;
3793     }
3794 }
3795
3796 /*
3797  * Send Telnet special codes. TS_EOF is useful for `plink', so you
3798  * can send an EOF and collect resulting output (e.g. `plink
3799  * hostname sort').
3800  */
3801 static void ssh_special (Telnet_Special code) {
3802     if (code == TS_EOF) {
3803         if (ssh_state != SSH_STATE_SESSION) {
3804             /*
3805              * Buffer the EOF in case we are pre-SESSION, so we can
3806              * send it as soon as we reach SESSION.
3807              */
3808             if (code == TS_EOF)
3809                 eof_needed = TRUE;
3810             return;
3811         }
3812         if (ssh_version == 1) {
3813             send_packet(SSH1_CMSG_EOF, PKT_END);
3814         } else {
3815             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3816             ssh2_pkt_adduint32(mainchan->remoteid);
3817             ssh2_pkt_send();
3818         }
3819         logevent("Sent EOF message");
3820     } else if (code == TS_PING) {
3821         if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3822             return;
3823         if (ssh_version == 1) {
3824             send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3825         } else {
3826             ssh2_pkt_init(SSH2_MSG_IGNORE);
3827             ssh2_pkt_addstring_start();
3828             ssh2_pkt_send();
3829         }
3830     } else {
3831         /* do nothing */
3832     }
3833 }
3834
3835 static Socket ssh_socket(void) { return s; }
3836
3837 static int ssh_sendok(void) { return ssh_send_ok; }
3838
3839 static int ssh_ldisc(int option) {
3840     if (option == LD_ECHO) return ssh_echoing;
3841     if (option == LD_EDIT) return ssh_editing;
3842     return FALSE;
3843 }
3844
3845 Backend ssh_backend = {
3846     ssh_init,
3847     ssh_send,
3848     ssh_size,
3849     ssh_special,
3850     ssh_socket,
3851     ssh_sendok,
3852     ssh_ldisc,
3853     22
3854 };