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