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