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