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