]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Increase length limit on SSH1_MSG_DEBUG; 70 chars is short enough to
[PuTTY.git] / ssh.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "tree234.h"
9 #include "ssh.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19                       if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20                       { fprintf(stderr, "%s\n", s); fflush(stderr); } }
21
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
24 {
25     va_list ap;
26     char stuff[200];
27
28     va_start(ap, fmt);
29     vsprintf(stuff, fmt, ap);
30     va_end(ap);
31     logevent(stuff);
32 }
33
34 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
35                           (s ? sk_close(s), s = NULL : 0), \
36                           logeventf msg, connection_fatal msg )
37
38 #define SSH1_MSG_DISCONNECT                       1     /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY                      2     /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY                     3     /* 0x3 */
41 #define SSH1_CMSG_USER                            4     /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA                        6     /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7     /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8     /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD                   9     /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY                     10    /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE                     11    /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL                      12    /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD                        13    /* 0xd */
50 #define SSH1_SMSG_SUCCESS                         14    /* 0xe */
51 #define SSH1_SMSG_FAILURE                         15    /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA                      16    /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA                     17    /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA                     18    /* 0x12 */
55 #define SSH1_CMSG_EOF                             19    /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS                     20    /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21    /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22    /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA                     23    /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE                    24    /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25    /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN                        27    /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST            28    /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN                        29    /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30    /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN                      31    /* 0x1f */
67 #define SSH1_MSG_IGNORE                           32    /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION               33    /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING          34    /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA                 35    /* 0x23 */
71 #define SSH1_MSG_DEBUG                            36    /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION             37    /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS                        39    /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE              40    /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE               41    /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD                      70    /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71    /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE             72    /* 0x48 */
79
80 #define SSH1_AUTH_TIS                             5     /* 0x5 */
81 #define SSH1_AUTH_CCARD                           16    /* 0x10 */
82
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER              1     /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED                 0     /* 0x1 */
86
87 #define SSH2_MSG_DISCONNECT                       1     /* 0x1 */
88 #define SSH2_MSG_IGNORE                           2     /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED                    3     /* 0x3 */
90 #define SSH2_MSG_DEBUG                            4     /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST                  5     /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT                   6     /* 0x6 */
93 #define SSH2_MSG_KEXINIT                          20    /* 0x14 */
94 #define SSH2_MSG_NEWKEYS                          21    /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT                       30    /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY                      31    /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST               30    /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP                 31    /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT                  32    /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY                 33    /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST                 50    /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE                 51    /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS                 52    /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER                  53    /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK                   60    /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60    /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST            60    /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE           61    /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST                   80    /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS                  81    /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE                  82    /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN                     90    /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91    /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE             92    /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93    /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA                     94    /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA            95    /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF                      96    /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE                    97    /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST                  98    /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS                  99    /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE                  100   /* 0x64 */
123
124 /*
125  * Packet type contexts, so that ssh2_pkt_type can correctly decode
126  * the ambiguous type numbers back into the correct type strings.
127  */
128 #define SSH2_PKTCTX_DHGROUP1         0x0001
129 #define SSH2_PKTCTX_DHGEX            0x0002
130 #define SSH2_PKTCTX_PUBLICKEY        0x0010
131 #define SSH2_PKTCTX_PASSWORD         0x0020
132 #define SSH2_PKTCTX_KBDINTER         0x0040
133 #define SSH2_PKTCTX_AUTH_MASK        0x00F0
134
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1   /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR            2     /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED       3     /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4    /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR                 5     /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR         6     /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE     7     /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8        /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE   9     /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST           10    /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION            11    /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS      12    /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER    13    /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14       /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME         15    /* 0xf */
150
151 static const char *const ssh2_disconnect_reasons[] = {
152     NULL,
153     "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154     "SSH_DISCONNECT_PROTOCOL_ERROR",
155     "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156     "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157     "SSH_DISCONNECT_MAC_ERROR",
158     "SSH_DISCONNECT_COMPRESSION_ERROR",
159     "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160     "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161     "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162     "SSH_DISCONNECT_CONNECTION_LOST",
163     "SSH_DISCONNECT_BY_APPLICATION",
164     "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165     "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166     "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167     "SSH_DISCONNECT_ILLEGAL_USER_NAME",
168 };
169
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1     /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED                  2     /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3     /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE               4     /* 0x4 */
174
175 #define SSH2_EXTENDED_DATA_STDERR                 1     /* 0x1 */
176
177 /*
178  * Various remote-bug flags.
179  */
180 #define BUG_CHOKES_ON_SSH1_IGNORE                 1
181 #define BUG_SSH2_HMAC                             2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD             4
183 #define BUG_CHOKES_ON_RSA                         8
184 #define BUG_SSH2_RSA_PADDING                     16
185 #define BUG_SSH2_DERIVEKEY                       32
186
187 static int ssh_pkt_ctx = 0;
188
189 #define translate(x) if (type == x) return #x
190 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
191 char *ssh1_pkt_type(int type)
192 {
193     translate(SSH1_MSG_DISCONNECT);
194     translate(SSH1_SMSG_PUBLIC_KEY);
195     translate(SSH1_CMSG_SESSION_KEY);
196     translate(SSH1_CMSG_USER);
197     translate(SSH1_CMSG_AUTH_RSA);
198     translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
199     translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
200     translate(SSH1_CMSG_AUTH_PASSWORD);
201     translate(SSH1_CMSG_REQUEST_PTY);
202     translate(SSH1_CMSG_WINDOW_SIZE);
203     translate(SSH1_CMSG_EXEC_SHELL);
204     translate(SSH1_CMSG_EXEC_CMD);
205     translate(SSH1_SMSG_SUCCESS);
206     translate(SSH1_SMSG_FAILURE);
207     translate(SSH1_CMSG_STDIN_DATA);
208     translate(SSH1_SMSG_STDOUT_DATA);
209     translate(SSH1_SMSG_STDERR_DATA);
210     translate(SSH1_CMSG_EOF);
211     translate(SSH1_SMSG_EXIT_STATUS);
212     translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
213     translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
214     translate(SSH1_MSG_CHANNEL_DATA);
215     translate(SSH1_MSG_CHANNEL_CLOSE);
216     translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
217     translate(SSH1_SMSG_X11_OPEN);
218     translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
219     translate(SSH1_MSG_PORT_OPEN);
220     translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
221     translate(SSH1_SMSG_AGENT_OPEN);
222     translate(SSH1_MSG_IGNORE);
223     translate(SSH1_CMSG_EXIT_CONFIRMATION);
224     translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
225     translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
226     translate(SSH1_MSG_DEBUG);
227     translate(SSH1_CMSG_REQUEST_COMPRESSION);
228     translate(SSH1_CMSG_AUTH_TIS);
229     translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
230     translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
231     translate(SSH1_CMSG_AUTH_CCARD);
232     translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
233     translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
234     return "unknown";
235 }
236 char *ssh2_pkt_type(int type)
237 {
238     translate(SSH2_MSG_DISCONNECT);
239     translate(SSH2_MSG_IGNORE);
240     translate(SSH2_MSG_UNIMPLEMENTED);
241     translate(SSH2_MSG_DEBUG);
242     translate(SSH2_MSG_SERVICE_REQUEST);
243     translate(SSH2_MSG_SERVICE_ACCEPT);
244     translate(SSH2_MSG_KEXINIT);
245     translate(SSH2_MSG_NEWKEYS);
246     translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
247     translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
248     translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
249     translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
250     translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
251     translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
252     translate(SSH2_MSG_USERAUTH_REQUEST);
253     translate(SSH2_MSG_USERAUTH_FAILURE);
254     translate(SSH2_MSG_USERAUTH_SUCCESS);
255     translate(SSH2_MSG_USERAUTH_BANNER);
256     translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
257     translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
258     translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
259     translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
260     translate(SSH2_MSG_GLOBAL_REQUEST);
261     translate(SSH2_MSG_REQUEST_SUCCESS);
262     translate(SSH2_MSG_REQUEST_FAILURE);
263     translate(SSH2_MSG_CHANNEL_OPEN);
264     translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
265     translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
266     translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
267     translate(SSH2_MSG_CHANNEL_DATA);
268     translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
269     translate(SSH2_MSG_CHANNEL_EOF);
270     translate(SSH2_MSG_CHANNEL_CLOSE);
271     translate(SSH2_MSG_CHANNEL_REQUEST);
272     translate(SSH2_MSG_CHANNEL_SUCCESS);
273     translate(SSH2_MSG_CHANNEL_FAILURE);
274     return "unknown";
275 }
276 #undef translate
277 #undef translatec
278
279 #define GET_32BIT(cp) \
280     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
281     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
282     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
283     ((unsigned long)(unsigned char)(cp)[3]))
284
285 #define PUT_32BIT(cp, value) { \
286     (cp)[0] = (unsigned char)((value) >> 24); \
287     (cp)[1] = (unsigned char)((value) >> 16); \
288     (cp)[2] = (unsigned char)((value) >> 8); \
289     (cp)[3] = (unsigned char)(value); }
290
291 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
292
293 /* Coroutine mechanics for the sillier bits of the code */
294 #define crBegin1        static int crLine = 0;
295 #define crBegin2        switch(crLine) { case 0:;
296 #define crBegin         crBegin1; crBegin2;
297 #define crFinish(z)     } crLine = 0; return (z)
298 #define crFinishV       } crLine = 0; return
299 #define crReturn(z)     \
300         do {\
301             crLine=__LINE__; return (z); case __LINE__:;\
302         } while (0)
303 #define crReturnV       \
304         do {\
305             crLine=__LINE__; return; case __LINE__:;\
306         } while (0)
307 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
308 #define crStopV         do{ crLine = 0; return; }while(0)
309 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
310 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
311
312 extern char *x11_init(Socket *, char *, void *);
313 extern void x11_close(Socket);
314 extern int x11_send(Socket, char *, int);
315 extern void x11_invent_auth(char *, int, char *, int);
316 extern void x11_unthrottle(Socket s);
317 extern void x11_override_throttle(Socket s, int enable);
318
319 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
320 extern char *pfd_addforward(char *desthost, int destport, int port);
321 extern void pfd_close(Socket s);
322 extern int pfd_send(Socket s, char *data, int len);
323 extern void pfd_confirm(Socket s);
324 extern void pfd_unthrottle(Socket s);
325 extern void pfd_override_throttle(Socket s, int enable);
326
327 static void ssh2_pkt_init(int pkt_type);
328 static void ssh2_pkt_addbool(unsigned char value);
329 static void ssh2_pkt_adduint32(unsigned long value);
330 static void ssh2_pkt_addstring_start(void);
331 static void ssh2_pkt_addstring_str(char *data);
332 static void ssh2_pkt_addstring_data(char *data, int len);
333 static void ssh2_pkt_addstring(char *data);
334 static char *ssh2_mpint_fmt(Bignum b, int *len);
335 static void ssh2_pkt_addmp(Bignum b);
336 static int ssh2_pkt_construct(void);
337 static void ssh2_pkt_send(void);
338
339 /*
340  * Buffer management constants. There are several of these for
341  * various different purposes:
342  * 
343  *  - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
344  *    on a local data stream before we throttle the whole SSH
345  *    connection (in SSH1 only). Throttling the whole connection is
346  *    pretty drastic so we set this high in the hope it won't
347  *    happen very often.
348  * 
349  *  - SSH_MAX_BACKLOG is the amount of backlog that must build up
350  *    on the SSH connection itself before we defensively throttle
351  *    _all_ local data streams. This is pretty drastic too (though
352  *    thankfully unlikely in SSH2 since the window mechanism should
353  *    ensure that the server never has any need to throttle its end
354  *    of the connection), so we set this high as well.
355  * 
356  *  - OUR_V2_WINSIZE is the maximum window size we present on SSH2
357  *    channels.
358  */
359
360 #define SSH1_BUFFER_LIMIT 32768
361 #define SSH_MAX_BACKLOG 32768
362 #define OUR_V2_WINSIZE 16384
363
364 const static struct ssh_kex *kex_algs[] = {
365     &ssh_diffiehellman_gex,
366     &ssh_diffiehellman
367 };
368
369 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
370
371 static void nullmac_key(unsigned char *key)
372 {
373 }
374 static void nullmac_generate(unsigned char *blk, int len,
375                              unsigned long seq)
376 {
377 }
378 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
379 {
380     return 1;
381 }
382 const static struct ssh_mac ssh_mac_none = {
383     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
384 };
385 const static struct ssh_mac *macs[] = {
386     &ssh_sha1, &ssh_md5, &ssh_mac_none
387 };
388 const static struct ssh_mac *buggymacs[] = {
389     &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
390 };
391
392 static void ssh_comp_none_init(void)
393 {
394 }
395 static int ssh_comp_none_block(unsigned char *block, int len,
396                                unsigned char **outblock, int *outlen)
397 {
398     return 0;
399 }
400 static int ssh_comp_none_disable(void)
401 {
402     return 0;
403 }
404 const static struct ssh_compress ssh_comp_none = {
405     "none",
406     ssh_comp_none_init, ssh_comp_none_block,
407     ssh_comp_none_init, ssh_comp_none_block,
408     ssh_comp_none_disable
409 };
410 extern const struct ssh_compress ssh_zlib;
411 const static struct ssh_compress *compressions[] = {
412     &ssh_zlib, &ssh_comp_none
413 };
414
415 enum {                                 /* channel types */
416     CHAN_MAINSESSION,
417     CHAN_X11,
418     CHAN_AGENT,
419     CHAN_SOCKDATA,
420     CHAN_SOCKDATA_DORMANT              /* one the remote hasn't confirmed */
421 };
422
423 /*
424  * 2-3-4 tree storing channels.
425  */
426 struct ssh_channel {
427     unsigned remoteid, localid;
428     int type;
429     int closes;
430     union {
431         struct ssh1_data_channel {
432             int throttling;
433         } v1;
434         struct ssh2_data_channel {
435             bufchain outbuffer;
436             unsigned remwindow, remmaxpkt;
437             unsigned locwindow;
438         } v2;
439     } v;
440     union {
441         struct ssh_agent_channel {
442             unsigned char *message;
443             unsigned char msglen[4];
444             int lensofar, totallen;
445         } a;
446         struct ssh_x11_channel {
447             Socket s;
448         } x11;
449         struct ssh_pfd_channel {
450             Socket s;
451         } pfd;
452     } u;
453 };
454
455 /*
456  * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
457  * 2 use this structure in different ways, reflecting SSH 2's
458  * altogether saner approach to port forwarding.
459  * 
460  * In SSH 1, you arrange a remote forwarding by sending the server
461  * the remote port number, and the local destination host:port.
462  * When a connection comes in, the server sends you back that
463  * host:port pair, and you connect to it. This is a ready-made
464  * security hole if you're not on the ball: a malicious server
465  * could send you back _any_ host:port pair, so if you trustingly
466  * connect to the address it gives you then you've just opened the
467  * entire inside of your corporate network just by connecting
468  * through it to a dodgy SSH server. Hence, we must store a list of
469  * host:port pairs we _are_ trying to forward to, and reject a
470  * connection request from the server if it's not in the list.
471  * 
472  * In SSH 2, each side of the connection minds its own business and
473  * doesn't send unnecessary information to the other. You arrange a
474  * remote forwarding by sending the server just the remote port
475  * number. When a connection comes in, the server tells you which
476  * of its ports was connected to; and _you_ have to remember what
477  * local host:port pair went with that port number.
478  * 
479  * Hence: in SSH 1 this structure stores host:port pairs we intend
480  * to allow connections to, and is indexed by those host:port
481  * pairs. In SSH 2 it stores a mapping from source port to
482  * destination host:port pair, and is indexed by source port.
483  */
484 struct ssh_rportfwd {
485     unsigned sport, dport;
486     char dhost[256];
487 };
488
489 struct Packet {
490     long length;
491     int type;
492     unsigned char *data;
493     unsigned char *body;
494     long savedpos;
495     long maxlen;
496 };
497
498 static SHA_State exhash, exhashbase;
499
500 static Socket s = NULL;
501
502 static unsigned char session_key[32];
503 static int ssh1_compressing;
504 static int ssh1_remote_protoflags;
505 static int ssh1_local_protoflags;
506 static int ssh_agentfwd_enabled;
507 static int ssh_X11_fwd_enabled;
508 static int ssh_remote_bugs;
509 static const struct ssh_cipher *cipher = NULL;
510 static const struct ssh2_cipher *cscipher = NULL;
511 static const struct ssh2_cipher *sccipher = NULL;
512 static const struct ssh_mac *csmac = NULL;
513 static const struct ssh_mac *scmac = NULL;
514 static const struct ssh_compress *cscomp = NULL;
515 static const struct ssh_compress *sccomp = NULL;
516 static const struct ssh_kex *kex = NULL;
517 static const struct ssh_signkey *hostkey = NULL;
518 static unsigned char ssh2_session_id[20];
519
520 static char *savedhost;
521 static int savedport;
522 static int ssh_send_ok;
523 static int ssh_echoing, ssh_editing;
524
525 static tree234 *ssh_channels;          /* indexed by local id */
526 static struct ssh_channel *mainchan;   /* primary session channel */
527 static int ssh_exitcode = -1;
528
529 static tree234 *ssh_rportfwds;
530
531 static enum {
532     SSH_STATE_PREPACKET,
533     SSH_STATE_BEFORE_SIZE,
534     SSH_STATE_INTERMED,
535     SSH_STATE_SESSION,
536     SSH_STATE_CLOSED
537 } ssh_state = SSH_STATE_PREPACKET;
538
539 static int size_needed = FALSE, eof_needed = FALSE;
540
541 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
542 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
543 static unsigned char *deferred_send_data = NULL;
544 static int deferred_len = 0, deferred_size = 0;
545
546 /*
547  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
548  * that fails. This variable is the means by which scp.c can reach
549  * into the SSH code and find out which one it got.
550  */
551 int ssh_fallback_cmd = 0;
552
553 static int ssh_version;
554 static int ssh1_throttle_count;
555 static int ssh_overall_bufsize;
556 static int ssh_throttled_all;
557 static int ssh1_stdout_throttling;
558 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
559 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
560 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
561 static void ssh_size(void);
562 static void ssh_special(Telnet_Special);
563 static int ssh2_try_send(struct ssh_channel *c);
564 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
565                                   int len);
566 static void ssh_throttle_all(int enable, int bufsize);
567 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
568 static int (*s_rdpkt) (unsigned char **data, int *datalen);
569 static int ssh_sendbuffer(void);
570
571 static struct rdpkt1_state_tag {
572     long len, pad, biglen, to_read;
573     unsigned long realcrc, gotcrc;
574     unsigned char *p;
575     int i;
576     int chunk;
577 } rdpkt1_state;
578
579 static struct rdpkt2_state_tag {
580     long len, pad, payload, packetlen, maclen;
581     int i;
582     int cipherblk;
583     unsigned long incoming_sequence;
584 } rdpkt2_state;
585
586 static int ssh_channelcmp(void *av, void *bv)
587 {
588     struct ssh_channel *a = (struct ssh_channel *) av;
589     struct ssh_channel *b = (struct ssh_channel *) bv;
590     if (a->localid < b->localid)
591         return -1;
592     if (a->localid > b->localid)
593         return +1;
594     return 0;
595 }
596 static int ssh_channelfind(void *av, void *bv)
597 {
598     unsigned *a = (unsigned *) av;
599     struct ssh_channel *b = (struct ssh_channel *) bv;
600     if (*a < b->localid)
601         return -1;
602     if (*a > b->localid)
603         return +1;
604     return 0;
605 }
606
607 static int ssh_rportcmp_ssh1(void *av, void *bv)
608 {
609     struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
610     struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
611     int i;
612     if ( (i = strcmp(a->dhost, b->dhost)) != 0)
613         return i < 0 ? -1 : +1;
614     if (a->dport > b->dport)
615         return +1;
616     if (a->dport < b->dport)
617         return -1;
618     return 0;
619 }
620
621 static int ssh_rportcmp_ssh2(void *av, void *bv)
622 {
623     struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
624     struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
625
626     if (a->sport > b->sport)
627         return +1;
628     if (a->sport < b->sport)
629         return -1;
630     return 0;
631 }
632
633 static int alloc_channel_id(void)
634 {
635     const unsigned CHANNEL_NUMBER_OFFSET = 256;
636     unsigned low, high, mid;
637     int tsize;
638     struct ssh_channel *c;
639
640     /*
641      * First-fit allocation of channel numbers: always pick the
642      * lowest unused one. To do this, binary-search using the
643      * counted B-tree to find the largest channel ID which is in a
644      * contiguous sequence from the beginning. (Precisely
645      * everything in that sequence must have ID equal to its tree
646      * index plus CHANNEL_NUMBER_OFFSET.)
647      */
648     tsize = count234(ssh_channels);
649
650     low = -1;
651     high = tsize;
652     while (high - low > 1) {
653         mid = (high + low) / 2;
654         c = index234(ssh_channels, mid);
655         if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
656             low = mid;                 /* this one is fine */
657         else
658             high = mid;                /* this one is past it */
659     }
660     /*
661      * Now low points to either -1, or the tree index of the
662      * largest ID in the initial sequence.
663      */
664     {
665         unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
666         assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
667     }
668     return low + 1 + CHANNEL_NUMBER_OFFSET;
669 }
670
671 static void c_write(char *buf, int len)
672 {
673     if ((flags & FLAG_STDERR)) {
674         int i;
675         for (i = 0; i < len; i++)
676             if (buf[i] != '\r')
677                 fputc(buf[i], stderr);
678         return;
679     }
680     from_backend(1, buf, len);
681 }
682
683 static void c_write_untrusted(char *buf, int len)
684 {
685     int i;
686     for (i = 0; i < len; i++) {
687         if (buf[i] == '\n')
688             c_write("\r\n", 2);
689         else if ((buf[i] & 0x60) || (buf[i] == '\r'))
690             c_write(buf + i, 1);
691     }
692 }
693
694 static void c_write_str(char *buf)
695 {
696     c_write(buf, strlen(buf));
697 }
698
699 /*
700  * Collect incoming data in the incoming packet buffer.
701  * Decipher and verify the packet when it is completely read.
702  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
703  * Update the *data and *datalen variables.
704  * Return the additional nr of bytes needed, or 0 when
705  * a complete packet is available.
706  */
707 static int ssh1_rdpkt(unsigned char **data, int *datalen)
708 {
709     struct rdpkt1_state_tag *st = &rdpkt1_state;
710
711     crBegin;
712
713   next_packet:
714
715     pktin.type = 0;
716     pktin.length = 0;
717
718     for (st->i = st->len = 0; st->i < 4; st->i++) {
719         while ((*datalen) == 0)
720             crReturn(4 - st->i);
721         st->len = (st->len << 8) + **data;
722         (*data)++, (*datalen)--;
723     }
724
725     st->pad = 8 - (st->len % 8);
726     st->biglen = st->len + st->pad;
727     pktin.length = st->len - 5;
728
729     if (pktin.maxlen < st->biglen) {
730         pktin.maxlen = st->biglen;
731         pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
732                       srealloc(pktin.data, st->biglen + APIEXTRA));
733         if (!pktin.data)
734             fatalbox("Out of memory");
735     }
736
737     st->to_read = st->biglen;
738     st->p = pktin.data;
739     while (st->to_read > 0) {
740         st->chunk = st->to_read;
741         while ((*datalen) == 0)
742             crReturn(st->to_read);
743         if (st->chunk > (*datalen))
744             st->chunk = (*datalen);
745         memcpy(st->p, *data, st->chunk);
746         *data += st->chunk;
747         *datalen -= st->chunk;
748         st->p += st->chunk;
749         st->to_read -= st->chunk;
750     }
751
752     if (cipher && detect_attack(pktin.data, st->biglen, NULL)) {
753         bombout(("Network attack (CRC compensation) detected!"));
754         crReturn(0);
755     }
756
757     if (cipher)
758         cipher->decrypt(pktin.data, st->biglen);
759
760     st->realcrc = crc32(pktin.data, st->biglen - 4);
761     st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
762     if (st->gotcrc != st->realcrc) {
763         bombout(("Incorrect CRC received on packet"));
764         crReturn(0);
765     }
766
767     pktin.body = pktin.data + st->pad + 1;
768
769     if (ssh1_compressing) {
770         unsigned char *decompblk;
771         int decomplen;
772         zlib_decompress_block(pktin.body - 1, pktin.length + 1,
773                               &decompblk, &decomplen);
774
775         if (pktin.maxlen < st->pad + decomplen) {
776             pktin.maxlen = st->pad + decomplen;
777             pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
778             pktin.body = pktin.data + st->pad + 1;
779             if (!pktin.data)
780                 fatalbox("Out of memory");
781         }
782
783         memcpy(pktin.body - 1, decompblk, decomplen);
784         sfree(decompblk);
785         pktin.length = decomplen - 1;
786     }
787
788     pktin.type = pktin.body[-1];
789
790     log_packet(PKT_INCOMING, pktin.type, ssh1_pkt_type(pktin.type),
791                pktin.body, pktin.length);
792
793     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
794         pktin.type == SSH1_SMSG_STDERR_DATA ||
795         pktin.type == SSH1_MSG_DEBUG ||
796         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
797         pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
798         long stringlen = GET_32BIT(pktin.body);
799         if (stringlen + 4 != pktin.length) {
800             bombout(("Received data packet with bogus string length"));
801             crReturn(0);
802         }
803     }
804
805     if (pktin.type == SSH1_MSG_DEBUG) {
806         /* log debug message */
807         char buf[512];
808         int stringlen = GET_32BIT(pktin.body);
809         strcpy(buf, "Remote debug message: ");
810         if (stringlen > 480)
811             stringlen = 480;
812         memcpy(buf + 8, pktin.body + 4, stringlen);
813         buf[8 + stringlen] = '\0';
814         logevent(buf);
815         goto next_packet;
816     } else if (pktin.type == SSH1_MSG_IGNORE) {
817         /* do nothing */
818         goto next_packet;
819     }
820
821     if (pktin.type == SSH1_MSG_DISCONNECT) {
822         /* log reason code in disconnect message */
823         char buf[256];
824         unsigned msglen = GET_32BIT(pktin.body);
825         unsigned nowlen;
826         strcpy(buf, "Remote sent disconnect: ");
827         nowlen = strlen(buf);
828         if (msglen > sizeof(buf) - nowlen - 1)
829             msglen = sizeof(buf) - nowlen - 1;
830         memcpy(buf + nowlen, pktin.body + 4, msglen);
831         buf[nowlen + msglen] = '\0';
832         /* logevent(buf); (this is now done within the bombout macro) */
833         bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
834         crReturn(0);
835     }
836
837     crFinish(0);
838 }
839
840 static int ssh2_rdpkt(unsigned char **data, int *datalen)
841 {
842     struct rdpkt2_state_tag *st = &rdpkt2_state;
843
844     crBegin;
845
846   next_packet:
847     pktin.type = 0;
848     pktin.length = 0;
849     if (sccipher)
850         st->cipherblk = sccipher->blksize;
851     else
852         st->cipherblk = 8;
853     if (st->cipherblk < 8)
854         st->cipherblk = 8;
855
856     if (pktin.maxlen < st->cipherblk) {
857         pktin.maxlen = st->cipherblk;
858         pktin.data =
859             (pktin.data ==
860              NULL ? smalloc(st->cipherblk +
861                             APIEXTRA) : srealloc(pktin.data,
862                                                  st->cipherblk +
863                                                  APIEXTRA));
864         if (!pktin.data)
865             fatalbox("Out of memory");
866     }
867
868     /*
869      * Acquire and decrypt the first block of the packet. This will
870      * contain the length and padding details.
871      */
872     for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
873         while ((*datalen) == 0)
874             crReturn(st->cipherblk - st->i);
875         pktin.data[st->i] = *(*data)++;
876         (*datalen)--;
877     }
878
879     if (sccipher)
880         sccipher->decrypt(pktin.data, st->cipherblk);
881
882     /*
883      * Now get the length and padding figures.
884      */
885     st->len = GET_32BIT(pktin.data);
886     st->pad = pktin.data[4];
887
888     /*
889      * _Completely_ silly lengths should be stomped on before they
890      * do us any more damage.
891      */
892     if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
893         bombout(("Incoming packet was garbled on decryption"));
894         crReturn(0);
895     }
896
897     /*
898      * This enables us to deduce the payload length.
899      */
900     st->payload = st->len - st->pad - 1;
901
902     pktin.length = st->payload + 5;
903
904     /*
905      * So now we can work out the total packet length.
906      */
907     st->packetlen = st->len + 4;
908     st->maclen = scmac ? scmac->len : 0;
909
910     /*
911      * Adjust memory allocation if packet is too big.
912      */
913     if (pktin.maxlen < st->packetlen + st->maclen) {
914         pktin.maxlen = st->packetlen + st->maclen;
915         pktin.data =
916             (pktin.data ==
917              NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
918                                                                 pktin.maxlen
919                                                                 +
920                                                                 APIEXTRA));
921         if (!pktin.data)
922             fatalbox("Out of memory");
923     }
924
925     /*
926      * Read and decrypt the remainder of the packet.
927      */
928     for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
929          st->i++) {
930         while ((*datalen) == 0)
931             crReturn(st->packetlen + st->maclen - st->i);
932         pktin.data[st->i] = *(*data)++;
933         (*datalen)--;
934     }
935     /* Decrypt everything _except_ the MAC. */
936     if (sccipher)
937         sccipher->decrypt(pktin.data + st->cipherblk,
938                           st->packetlen - st->cipherblk);
939
940     /*
941      * Check the MAC.
942      */
943     if (scmac
944         && !scmac->verify(pktin.data, st->len + 4,
945                           st->incoming_sequence)) {
946         bombout(("Incorrect MAC received on packet"));
947         crReturn(0);
948     }
949     st->incoming_sequence++;           /* whether or not we MACed */
950
951     /*
952      * Decompress packet payload.
953      */
954     {
955         unsigned char *newpayload;
956         int newlen;
957         if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
958                                          &newpayload, &newlen)) {
959             if (pktin.maxlen < newlen + 5) {
960                 pktin.maxlen = newlen + 5;
961                 pktin.data =
962                     (pktin.data ==
963                      NULL ? smalloc(pktin.maxlen +
964                                     APIEXTRA) : srealloc(pktin.data,
965                                                          pktin.maxlen +
966                                                          APIEXTRA));
967                 if (!pktin.data)
968                     fatalbox("Out of memory");
969             }
970             pktin.length = 5 + newlen;
971             memcpy(pktin.data + 5, newpayload, newlen);
972             sfree(newpayload);
973         }
974     }
975
976     pktin.savedpos = 6;
977     pktin.type = pktin.data[5];
978
979     log_packet(PKT_INCOMING, pktin.type, ssh2_pkt_type(pktin.type),
980                pktin.data+6, pktin.length-6);
981
982     switch (pktin.type) {
983         /*
984          * These packets we must handle instantly.
985          */
986       case SSH2_MSG_DISCONNECT:
987         {
988             /* log reason code in disconnect message */
989             char buf[256];
990             int reason = GET_32BIT(pktin.data + 6);
991             unsigned msglen = GET_32BIT(pktin.data + 10);
992             unsigned nowlen;
993             if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
994                 sprintf(buf, "Received disconnect message (%s)",
995                         ssh2_disconnect_reasons[reason]);
996             } else {
997                 sprintf(buf, "Received disconnect message (unknown type %d)",
998                         reason);
999             }
1000             logevent(buf);
1001             strcpy(buf, "Disconnection message text: ");
1002             nowlen = strlen(buf);
1003             if (msglen > sizeof(buf) - nowlen - 1)
1004                 msglen = sizeof(buf) - nowlen - 1;
1005             memcpy(buf + nowlen, pktin.data + 14, msglen);
1006             buf[nowlen + msglen] = '\0';
1007             logevent(buf);
1008             bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1009                      reason,
1010                      (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1011                      ssh2_disconnect_reasons[reason] : "unknown",
1012                      buf+nowlen));
1013             crReturn(0);
1014         }
1015         break;
1016       case SSH2_MSG_IGNORE:
1017         goto next_packet;
1018       case SSH2_MSG_DEBUG:
1019         {
1020             /* log the debug message */
1021             char buf[512];
1022             /* int display = pktin.body[6]; */
1023             int stringlen = GET_32BIT(pktin.data+7);
1024             int prefix;
1025             strcpy(buf, "Remote debug message: ");
1026             prefix = strlen(buf);
1027             if (stringlen > sizeof(buf)-prefix-1)
1028                 stringlen = sizeof(buf)-prefix-1;
1029             memcpy(buf + prefix, pktin.data + 11, stringlen);
1030             buf[prefix + stringlen] = '\0';
1031             logevent(buf);
1032         }
1033         goto next_packet;              /* FIXME: print the debug message */
1034
1035         /*
1036          * These packets we need do nothing about here.
1037          */
1038       case SSH2_MSG_UNIMPLEMENTED:
1039       case SSH2_MSG_SERVICE_REQUEST:
1040       case SSH2_MSG_SERVICE_ACCEPT:
1041       case SSH2_MSG_KEXINIT:
1042       case SSH2_MSG_NEWKEYS:
1043       case SSH2_MSG_KEXDH_INIT:
1044       case SSH2_MSG_KEXDH_REPLY:
1045       /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1046       /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1047       case SSH2_MSG_KEX_DH_GEX_INIT:
1048       case SSH2_MSG_KEX_DH_GEX_REPLY:
1049       case SSH2_MSG_USERAUTH_REQUEST:
1050       case SSH2_MSG_USERAUTH_FAILURE:
1051       case SSH2_MSG_USERAUTH_SUCCESS:
1052       case SSH2_MSG_USERAUTH_BANNER:
1053       case SSH2_MSG_USERAUTH_PK_OK:
1054       /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1055       /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1056       case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1057       case SSH2_MSG_GLOBAL_REQUEST:
1058       case SSH2_MSG_REQUEST_SUCCESS:
1059       case SSH2_MSG_REQUEST_FAILURE:
1060       case SSH2_MSG_CHANNEL_OPEN:
1061       case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1062       case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1063       case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1064       case SSH2_MSG_CHANNEL_DATA:
1065       case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1066       case SSH2_MSG_CHANNEL_EOF:
1067       case SSH2_MSG_CHANNEL_CLOSE:
1068       case SSH2_MSG_CHANNEL_REQUEST:
1069       case SSH2_MSG_CHANNEL_SUCCESS:
1070       case SSH2_MSG_CHANNEL_FAILURE:
1071         break;
1072
1073         /*
1074          * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1075          */
1076       default:
1077         ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1078         ssh2_pkt_adduint32(st->incoming_sequence - 1);
1079         ssh2_pkt_send();
1080         break;
1081     }
1082
1083     crFinish(0);
1084 }
1085
1086 static void ssh1_pktout_size(int len)
1087 {
1088     int pad, biglen;
1089
1090     len += 5;                          /* type and CRC */
1091     pad = 8 - (len % 8);
1092     biglen = len + pad;
1093
1094     pktout.length = len - 5;
1095     if (pktout.maxlen < biglen) {
1096         pktout.maxlen = biglen;
1097 #ifdef MSCRYPTOAPI
1098         /* Allocate enough buffer space for extra block
1099          * for MS CryptEncrypt() */
1100         pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
1101                        srealloc(pktout.data, biglen + 12));
1102 #else
1103         pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
1104                        srealloc(pktout.data, biglen + 4));
1105 #endif
1106         if (!pktout.data)
1107             fatalbox("Out of memory");
1108     }
1109     pktout.body = pktout.data + 4 + pad + 1;
1110 }
1111
1112 static void s_wrpkt_start(int type, int len)
1113 {
1114     ssh1_pktout_size(len);
1115     pktout.type = type;
1116 }
1117
1118 static int s_wrpkt_prepare(void)
1119 {
1120     int pad, len, biglen, i;
1121     unsigned long crc;
1122
1123     pktout.body[-1] = pktout.type;
1124
1125     log_packet(PKT_OUTGOING, pktout.type, ssh1_pkt_type(pktout.type),
1126                pktout.body, pktout.length);
1127
1128     if (ssh1_compressing) {
1129         unsigned char *compblk;
1130         int complen;
1131         zlib_compress_block(pktout.body - 1, pktout.length + 1,
1132                             &compblk, &complen);
1133         ssh1_pktout_size(complen - 1);
1134         memcpy(pktout.body - 1, compblk, complen);
1135         sfree(compblk);
1136     }
1137
1138     len = pktout.length + 5;           /* type and CRC */
1139     pad = 8 - (len % 8);
1140     biglen = len + pad;
1141
1142     for (i = 0; i < pad; i++)
1143         pktout.data[i + 4] = random_byte();
1144     crc = crc32(pktout.data + 4, biglen - 4);
1145     PUT_32BIT(pktout.data + biglen, crc);
1146     PUT_32BIT(pktout.data, len);
1147
1148     if (cipher)
1149         cipher->encrypt(pktout.data + 4, biglen);
1150
1151     return biglen + 4;
1152 }
1153
1154 static void s_wrpkt(void)
1155 {
1156     int len, backlog;
1157     len = s_wrpkt_prepare();
1158     backlog = sk_write(s, pktout.data, len);
1159     if (backlog > SSH_MAX_BACKLOG)
1160         ssh_throttle_all(1, backlog);
1161 }
1162
1163 static void s_wrpkt_defer(void)
1164 {
1165     int len;
1166     len = s_wrpkt_prepare();
1167     if (deferred_len + len > deferred_size) {
1168         deferred_size = deferred_len + len + 128;
1169         deferred_send_data = srealloc(deferred_send_data, deferred_size);
1170     }
1171     memcpy(deferred_send_data + deferred_len, pktout.data, len);
1172     deferred_len += len;
1173 }
1174
1175 /*
1176  * Construct a packet with the specified contents.
1177  */
1178 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1179 {
1180     unsigned char *p, *argp, argchar;
1181     unsigned long argint;
1182     int pktlen, argtype, arglen;
1183     Bignum bn;
1184
1185     pktlen = 0;
1186     while ((argtype = va_arg(ap1, int)) != PKT_END) {
1187         switch (argtype) {
1188           case PKT_INT:
1189             (void) va_arg(ap1, int);
1190             pktlen += 4;
1191             break;
1192           case PKT_CHAR:
1193             (void) va_arg(ap1, char);
1194             pktlen++;
1195             break;
1196           case PKT_DATA:
1197             (void) va_arg(ap1, unsigned char *);
1198             arglen = va_arg(ap1, int);
1199             pktlen += arglen;
1200             break;
1201           case PKT_STR:
1202             argp = va_arg(ap1, unsigned char *);
1203             arglen = strlen(argp);
1204             pktlen += 4 + arglen;
1205             break;
1206           case PKT_BIGNUM:
1207             bn = va_arg(ap1, Bignum);
1208             pktlen += ssh1_bignum_length(bn);
1209             break;
1210           default:
1211             assert(0);
1212         }
1213     }
1214
1215     s_wrpkt_start(pkttype, pktlen);
1216     p = pktout.body;
1217
1218     while ((argtype = va_arg(ap2, int)) != PKT_END) {
1219         switch (argtype) {
1220           case PKT_INT:
1221             argint = va_arg(ap2, int);
1222             PUT_32BIT(p, argint);
1223             p += 4;
1224             break;
1225           case PKT_CHAR:
1226             argchar = va_arg(ap2, unsigned char);
1227             *p = argchar;
1228             p++;
1229             break;
1230           case PKT_DATA:
1231             argp = va_arg(ap2, unsigned char *);
1232             arglen = va_arg(ap2, int);
1233             memcpy(p, argp, arglen);
1234             p += arglen;
1235             break;
1236           case PKT_STR:
1237             argp = va_arg(ap2, unsigned char *);
1238             arglen = strlen(argp);
1239             PUT_32BIT(p, arglen);
1240             memcpy(p + 4, argp, arglen);
1241             p += 4 + arglen;
1242             break;
1243           case PKT_BIGNUM:
1244             bn = va_arg(ap2, Bignum);
1245             p += ssh1_write_bignum(p, bn);
1246             break;
1247         }
1248     }
1249 }
1250
1251 static void send_packet(int pkttype, ...)
1252 {
1253     va_list ap1, ap2;
1254     va_start(ap1, pkttype);
1255     va_start(ap2, pkttype);
1256     construct_packet(pkttype, ap1, ap2);
1257     s_wrpkt();
1258 }
1259
1260 static void defer_packet(int pkttype, ...)
1261 {
1262     va_list ap1, ap2;
1263     va_start(ap1, pkttype);
1264     va_start(ap2, pkttype);
1265     construct_packet(pkttype, ap1, ap2);
1266     s_wrpkt_defer();
1267 }
1268
1269 static int ssh_versioncmp(char *a, char *b)
1270 {
1271     char *ae, *be;
1272     unsigned long av, bv;
1273
1274     av = strtoul(a, &ae, 10);
1275     bv = strtoul(b, &be, 10);
1276     if (av != bv)
1277         return (av < bv ? -1 : +1);
1278     if (*ae == '.')
1279         ae++;
1280     if (*be == '.')
1281         be++;
1282     av = strtoul(ae, &ae, 10);
1283     bv = strtoul(be, &be, 10);
1284     if (av != bv)
1285         return (av < bv ? -1 : +1);
1286     return 0;
1287 }
1288
1289
1290 /*
1291  * Utility routines for putting an SSH-protocol `string' and
1292  * `uint32' into a SHA state.
1293  */
1294 #include <stdio.h>
1295 static void sha_string(SHA_State * s, void *str, int len)
1296 {
1297     unsigned char lenblk[4];
1298     PUT_32BIT(lenblk, len);
1299     SHA_Bytes(s, lenblk, 4);
1300     SHA_Bytes(s, str, len);
1301 }
1302
1303 static void sha_uint32(SHA_State * s, unsigned i)
1304 {
1305     unsigned char intblk[4];
1306     PUT_32BIT(intblk, i);
1307     SHA_Bytes(s, intblk, 4);
1308 }
1309
1310 /*
1311  * SSH2 packet construction functions.
1312  */
1313 static void ssh2_pkt_ensure(int length)
1314 {
1315     if (pktout.maxlen < length) {
1316         pktout.maxlen = length + 256;
1317         pktout.data =
1318             (pktout.data ==
1319              NULL ? smalloc(pktout.maxlen +
1320                             APIEXTRA) : srealloc(pktout.data,
1321                                                  pktout.maxlen +
1322                                                  APIEXTRA));
1323         if (!pktout.data)
1324             fatalbox("Out of memory");
1325     }
1326 }
1327 static void ssh2_pkt_adddata(void *data, int len)
1328 {
1329     pktout.length += len;
1330     ssh2_pkt_ensure(pktout.length);
1331     memcpy(pktout.data + pktout.length - len, data, len);
1332 }
1333 static void ssh2_pkt_addbyte(unsigned char byte)
1334 {
1335     ssh2_pkt_adddata(&byte, 1);
1336 }
1337 static void ssh2_pkt_init(int pkt_type)
1338 {
1339     pktout.length = 5;
1340     ssh2_pkt_addbyte((unsigned char) pkt_type);
1341 }
1342 static void ssh2_pkt_addbool(unsigned char value)
1343 {
1344     ssh2_pkt_adddata(&value, 1);
1345 }
1346 static void ssh2_pkt_adduint32(unsigned long value)
1347 {
1348     unsigned char x[4];
1349     PUT_32BIT(x, value);
1350     ssh2_pkt_adddata(x, 4);
1351 }
1352 static void ssh2_pkt_addstring_start(void)
1353 {
1354     ssh2_pkt_adduint32(0);
1355     pktout.savedpos = pktout.length;
1356 }
1357 static void ssh2_pkt_addstring_str(char *data)
1358 {
1359     ssh2_pkt_adddata(data, strlen(data));
1360     PUT_32BIT(pktout.data + pktout.savedpos - 4,
1361               pktout.length - pktout.savedpos);
1362 }
1363 static void ssh2_pkt_addstring_data(char *data, int len)
1364 {
1365     ssh2_pkt_adddata(data, len);
1366     PUT_32BIT(pktout.data + pktout.savedpos - 4,
1367               pktout.length - pktout.savedpos);
1368 }
1369 static void ssh2_pkt_addstring(char *data)
1370 {
1371     ssh2_pkt_addstring_start();
1372     ssh2_pkt_addstring_str(data);
1373 }
1374 static char *ssh2_mpint_fmt(Bignum b, int *len)
1375 {
1376     unsigned char *p;
1377     int i, n = (bignum_bitcount(b) + 7) / 8;
1378     p = smalloc(n + 1);
1379     if (!p)
1380         fatalbox("out of memory");
1381     p[0] = 0;
1382     for (i = 1; i <= n; i++)
1383         p[i] = bignum_byte(b, n - i);
1384     i = 0;
1385     while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1386         i++;
1387     memmove(p, p + i, n + 1 - i);
1388     *len = n + 1 - i;
1389     return p;
1390 }
1391 static void ssh2_pkt_addmp(Bignum b)
1392 {
1393     unsigned char *p;
1394     int len;
1395     p = ssh2_mpint_fmt(b, &len);
1396     ssh2_pkt_addstring_start();
1397     ssh2_pkt_addstring_data(p, len);
1398     sfree(p);
1399 }
1400
1401 /*
1402  * Construct an SSH2 final-form packet: compress it, encrypt it,
1403  * put the MAC on it. Final packet, ready to be sent, is stored in
1404  * pktout.data. Total length is returned.
1405  */
1406 static int ssh2_pkt_construct(void)
1407 {
1408     int cipherblk, maclen, padding, i;
1409     static unsigned long outgoing_sequence = 0;
1410
1411     log_packet(PKT_OUTGOING, pktout.data[5], ssh2_pkt_type(pktout.data[5]),
1412                pktout.data + 6, pktout.length - 6);
1413
1414     /*
1415      * Compress packet payload.
1416      */
1417     {
1418         unsigned char *newpayload;
1419         int newlen;
1420         if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1421                                        &newpayload, &newlen)) {
1422             pktout.length = 5;
1423             ssh2_pkt_adddata(newpayload, newlen);
1424             sfree(newpayload);
1425         }
1426     }
1427
1428     /*
1429      * Add padding. At least four bytes, and must also bring total
1430      * length (minus MAC) up to a multiple of the block size.
1431      */
1432     cipherblk = cscipher ? cscipher->blksize : 8;       /* block size */
1433     cipherblk = cipherblk < 8 ? 8 : cipherblk;  /* or 8 if blksize < 8 */
1434     padding = 4;
1435     padding +=
1436         (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1437     maclen = csmac ? csmac->len : 0;
1438     ssh2_pkt_ensure(pktout.length + padding + maclen);
1439     pktout.data[4] = padding;
1440     for (i = 0; i < padding; i++)
1441         pktout.data[pktout.length + i] = random_byte();
1442     PUT_32BIT(pktout.data, pktout.length + padding - 4);
1443     if (csmac)
1444         csmac->generate(pktout.data, pktout.length + padding,
1445                         outgoing_sequence);
1446     outgoing_sequence++;               /* whether or not we MACed */
1447
1448     if (cscipher)
1449         cscipher->encrypt(pktout.data, pktout.length + padding);
1450
1451     /* Ready-to-send packet starts at pktout.data. We return length. */
1452     return pktout.length + padding + maclen;
1453 }
1454
1455 /*
1456  * Construct and send an SSH2 packet immediately.
1457  */
1458 static void ssh2_pkt_send(void)
1459 {
1460     int len;
1461     int backlog;
1462     len = ssh2_pkt_construct();
1463     backlog = sk_write(s, pktout.data, len);
1464     if (backlog > SSH_MAX_BACKLOG)
1465         ssh_throttle_all(1, backlog);
1466 }
1467
1468 /*
1469  * Construct an SSH2 packet and add it to a deferred data block.
1470  * Useful for sending multiple packets in a single sk_write() call,
1471  * to prevent a traffic-analysing listener from being able to work
1472  * out the length of any particular packet (such as the password
1473  * packet).
1474  * 
1475  * Note that because SSH2 sequence-numbers its packets, this can
1476  * NOT be used as an m4-style `defer' allowing packets to be
1477  * constructed in one order and sent in another.
1478  */
1479 static void ssh2_pkt_defer(void)
1480 {
1481     int len = ssh2_pkt_construct();
1482     if (deferred_len + len > deferred_size) {
1483         deferred_size = deferred_len + len + 128;
1484         deferred_send_data = srealloc(deferred_send_data, deferred_size);
1485     }
1486     memcpy(deferred_send_data + deferred_len, pktout.data, len);
1487     deferred_len += len;
1488 }
1489
1490 /*
1491  * Send the whole deferred data block constructed by
1492  * ssh2_pkt_defer() or SSH1's defer_packet().
1493  */
1494 static void ssh_pkt_defersend(void)
1495 {
1496     int backlog;
1497     backlog = sk_write(s, deferred_send_data, deferred_len);
1498     deferred_len = deferred_size = 0;
1499     sfree(deferred_send_data);
1500     deferred_send_data = NULL;
1501     if (backlog > SSH_MAX_BACKLOG)
1502         ssh_throttle_all(1, backlog);
1503 }
1504
1505 #if 0
1506 void bndebug(char *string, Bignum b)
1507 {
1508     unsigned char *p;
1509     int i, len;
1510     p = ssh2_mpint_fmt(b, &len);
1511     debug(("%s", string));
1512     for (i = 0; i < len; i++)
1513         debug((" %02x", p[i]));
1514     debug(("\n"));
1515     sfree(p);
1516 }
1517 #endif
1518
1519 static void sha_mpint(SHA_State * s, Bignum b)
1520 {
1521     unsigned char *p;
1522     int len;
1523     p = ssh2_mpint_fmt(b, &len);
1524     sha_string(s, p, len);
1525     sfree(p);
1526 }
1527
1528 /*
1529  * SSH2 packet decode functions.
1530  */
1531 static unsigned long ssh2_pkt_getuint32(void)
1532 {
1533     unsigned long value;
1534     if (pktin.length - pktin.savedpos < 4)
1535         return 0;                      /* arrgh, no way to decline (FIXME?) */
1536     value = GET_32BIT(pktin.data + pktin.savedpos);
1537     pktin.savedpos += 4;
1538     return value;
1539 }
1540 static int ssh2_pkt_getbool(void)
1541 {
1542     unsigned long value;
1543     if (pktin.length - pktin.savedpos < 1)
1544         return 0;                      /* arrgh, no way to decline (FIXME?) */
1545     value = pktin.data[pktin.savedpos] != 0;
1546     pktin.savedpos++;
1547     return value;
1548 }
1549 static void ssh2_pkt_getstring(char **p, int *length)
1550 {
1551     *p = NULL;
1552     *length = 0;
1553     if (pktin.length - pktin.savedpos < 4)
1554         return;
1555     *length = GET_32BIT(pktin.data + pktin.savedpos);
1556     pktin.savedpos += 4;
1557     if (pktin.length - pktin.savedpos < *length)
1558         return;
1559     *p = pktin.data + pktin.savedpos;
1560     pktin.savedpos += *length;
1561 }
1562 static Bignum ssh2_pkt_getmp(void)
1563 {
1564     char *p;
1565     int length;
1566     Bignum b;
1567
1568     ssh2_pkt_getstring(&p, &length);
1569     if (!p)
1570         return NULL;
1571     if (p[0] & 0x80) {
1572         bombout(("internal error: Can't handle negative mpints"));
1573         return NULL;
1574     }
1575     b = bignum_from_bytes(p, length);
1576     return b;
1577 }
1578
1579 /*
1580  * Helper function to add an SSH2 signature blob to a packet.
1581  * Expects to be shown the public key blob as well as the signature
1582  * blob. Normally works just like ssh2_pkt_addstring, but will
1583  * fiddle with the signature packet if necessary for
1584  * BUG_SSH2_RSA_PADDING.
1585  */
1586 static void ssh2_add_sigblob(void *pkblob_v, int pkblob_len,
1587                              void *sigblob_v, int sigblob_len)
1588 {
1589     unsigned char *pkblob = (unsigned char *)pkblob_v;
1590     unsigned char *sigblob = (unsigned char *)sigblob_v;
1591
1592     /* dmemdump(pkblob, pkblob_len); */
1593     /* dmemdump(sigblob, sigblob_len); */
1594
1595     /*
1596      * See if this is in fact an ssh-rsa signature and a buggy
1597      * server; otherwise we can just do this the easy way.
1598      */
1599     if ((ssh_remote_bugs & BUG_SSH2_RSA_PADDING) &&
1600         (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1601         int pos, len, siglen;
1602
1603         /*
1604          * Find the byte length of the modulus.
1605          */
1606
1607         pos = 4+7;                     /* skip over "ssh-rsa" */
1608         pos += 4 + GET_32BIT(pkblob+pos);   /* skip over exponent */
1609         len = GET_32BIT(pkblob+pos);   /* find length of modulus */
1610         pos += 4;                      /* find modulus itself */
1611         while (len > 0 && pkblob[pos] == 0)
1612             len--, pos++;
1613         /* debug(("modulus length is %d\n", len)); */
1614
1615         /*
1616          * Now find the signature integer.
1617          */
1618         pos = 4+7;                     /* skip over "ssh-rsa" */
1619         siglen = GET_32BIT(sigblob+pos);
1620         /* debug(("signature length is %d\n", siglen)); */
1621
1622         if (len != siglen) {
1623             unsigned char newlen[4];
1624             ssh2_pkt_addstring_start();
1625             ssh2_pkt_addstring_data(sigblob, pos);
1626             /* dmemdump(sigblob, pos); */
1627             pos += 4;                  /* point to start of actual sig */
1628             PUT_32BIT(newlen, len);
1629             ssh2_pkt_addstring_data(newlen, 4);
1630             /* dmemdump(newlen, 4); */
1631             newlen[0] = 0;
1632             while (len-- > siglen) {
1633                 ssh2_pkt_addstring_data(newlen, 1);
1634                 /* dmemdump(newlen, 1); */
1635             }
1636             ssh2_pkt_addstring_data(sigblob+pos, siglen);
1637             /* dmemdump(sigblob+pos, siglen); */
1638             return;
1639         }
1640
1641         /* Otherwise fall through and do it the easy way. */
1642     }
1643
1644     ssh2_pkt_addstring_start();
1645     ssh2_pkt_addstring_data(sigblob, sigblob_len);
1646 }
1647
1648 /*
1649  * Examine the remote side's version string and compare it against
1650  * a list of known buggy implementations.
1651  */
1652 static void ssh_detect_bugs(char *vstring)
1653 {
1654     char *imp;                         /* pointer to implementation part */
1655     imp = vstring;
1656     imp += strcspn(imp, "-");
1657     if (*imp) imp++;
1658     imp += strcspn(imp, "-");
1659     if (*imp) imp++;
1660
1661     ssh_remote_bugs = 0;
1662
1663     if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1664         !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1665         !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")) {
1666         /*
1667          * These versions don't support SSH1_MSG_IGNORE, so we have
1668          * to use a different defence against password length
1669          * sniffing.
1670          */
1671         ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1672         logevent("We believe remote version has SSH1 ignore bug");
1673     }
1674
1675     if (!strcmp(imp, "Cisco-1.25")) {
1676         /*
1677          * These versions need a plain password sent; they can't
1678          * handle having a null and a random length of data after
1679          * the password.
1680          */
1681         ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1682         logevent("We believe remote version needs a plain SSH1 password");
1683     }
1684
1685     if (!strcmp(imp, "Cisco-1.25")) {
1686         /*
1687          * These versions apparently have no clue whatever about
1688          * RSA authentication and will panic and die if they see
1689          * an AUTH_RSA message.
1690          */
1691         ssh_remote_bugs |= BUG_CHOKES_ON_RSA;
1692         logevent("We believe remote version can't handle RSA authentication");
1693     }
1694
1695     if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1696         !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1697         !strncmp(imp, "2.1 ", 4)) {
1698         /*
1699          * These versions have the HMAC bug.
1700          */
1701         ssh_remote_bugs |= BUG_SSH2_HMAC;
1702         logevent("We believe remote version has SSH2 HMAC bug");
1703     }
1704
1705     if (!strncmp(imp, "2.0.", 4)) {
1706         /*
1707          * These versions have the key-derivation bug (failing to
1708          * include the literal shared secret in the hashes that
1709          * generate the keys).
1710          */
1711         ssh_remote_bugs |= BUG_SSH2_DERIVEKEY;
1712         logevent("We believe remote version has SSH2 key-derivation bug");
1713     }
1714
1715     if ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1716         (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')) {
1717         /*
1718          * These versions have the SSH2 RSA padding bug.
1719          */
1720         ssh_remote_bugs |= BUG_SSH2_RSA_PADDING;
1721         logevent("We believe remote version has SSH2 RSA padding bug");
1722     }
1723 }
1724
1725 static int do_ssh_init(unsigned char c)
1726 {
1727     static int vslen;
1728     static char version[10];
1729     static char *vstring;
1730     static int vstrsize;
1731     static char *vlog;
1732     static int i;
1733     static int proto1, proto2;
1734
1735     crBegin;
1736
1737     /* Search for the string "SSH-" in the input. */
1738     i = 0;
1739     while (1) {
1740         static const int transS[] = { 1, 2, 2, 1 };
1741         static const int transH[] = { 0, 0, 3, 0 };
1742         static const int transminus[] = { 0, 0, 0, -1 };
1743         if (c == 'S')
1744             i = transS[i];
1745         else if (c == 'H')
1746             i = transH[i];
1747         else if (c == '-')
1748             i = transminus[i];
1749         else
1750             i = 0;
1751         if (i < 0)
1752             break;
1753         crReturn(1);                   /* get another character */
1754     }
1755
1756     vstrsize = 16;
1757     vstring = smalloc(vstrsize);
1758     strcpy(vstring, "SSH-");
1759     vslen = 4;
1760     i = 0;
1761     while (1) {
1762         crReturn(1);                   /* get another char */
1763         if (vslen >= vstrsize - 1) {
1764             vstrsize += 16;
1765             vstring = srealloc(vstring, vstrsize);
1766         }
1767         vstring[vslen++] = c;
1768         if (i >= 0) {
1769             if (c == '-') {
1770                 version[i] = '\0';
1771                 i = -1;
1772             } else if (i < sizeof(version) - 1)
1773                 version[i++] = c;
1774         } else if (c == '\n')
1775             break;
1776     }
1777
1778     ssh_agentfwd_enabled = FALSE;
1779     rdpkt2_state.incoming_sequence = 0;
1780
1781     vstring[vslen] = 0;
1782     vlog = smalloc(20 + vslen);
1783     vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1784     sprintf(vlog, "Server version: %s", vstring);
1785     logevent(vlog);
1786     ssh_detect_bugs(vstring);
1787     sfree(vlog);
1788
1789     /*
1790      * Decide which SSH protocol version to support.
1791      */
1792
1793     /* Anything strictly below "2.0" means protocol 1 is supported. */
1794     proto1 = ssh_versioncmp(version, "2.0") < 0;
1795     /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1796     proto2 = ssh_versioncmp(version, "1.99") >= 0;
1797
1798     if (cfg.sshprot == 0 && !proto1) {
1799         bombout(("SSH protocol version 1 required by user but not provided by server"));
1800         crReturn(0);
1801     }
1802     if (cfg.sshprot == 3 && !proto2) {
1803         bombout(("SSH protocol version 2 required by user but not provided by server"));
1804         crReturn(0);
1805     }
1806
1807     if (proto2 && (cfg.sshprot >= 2 || !proto1)) {
1808         /*
1809          * Use v2 protocol.
1810          */
1811         char verstring[80], vlog[100];
1812         sprintf(verstring, "SSH-2.0-%s", sshver);
1813         SHA_Init(&exhashbase);
1814         /*
1815          * Hash our version string and their version string.
1816          */
1817         sha_string(&exhashbase, verstring, strlen(verstring));
1818         sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1819         sprintf(vlog, "We claim version: %s", verstring);
1820         logevent(vlog);
1821         strcat(verstring, "\n");
1822         logevent("Using SSH protocol version 2");
1823         sk_write(s, verstring, strlen(verstring));
1824         ssh_protocol = ssh2_protocol;
1825         ssh_version = 2;
1826         s_rdpkt = ssh2_rdpkt;
1827     } else {
1828         /*
1829          * Use v1 protocol.
1830          */
1831         char verstring[80], vlog[100];
1832         sprintf(verstring, "SSH-%s-%s",
1833                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1834                 sshver);
1835         sprintf(vlog, "We claim version: %s", verstring);
1836         logevent(vlog);
1837         strcat(verstring, "\n");
1838
1839         logevent("Using SSH protocol version 1");
1840         sk_write(s, verstring, strlen(verstring));
1841         ssh_protocol = ssh1_protocol;
1842         ssh_version = 1;
1843         s_rdpkt = ssh1_rdpkt;
1844     }
1845     ssh_state = SSH_STATE_BEFORE_SIZE;
1846
1847     sfree(vstring);
1848
1849     crFinish(0);
1850 }
1851
1852 static void ssh_gotdata(unsigned char *data, int datalen)
1853 {
1854     crBegin;
1855
1856     /*
1857      * To begin with, feed the characters one by one to the
1858      * protocol initialisation / selection function do_ssh_init().
1859      * When that returns 0, we're done with the initial greeting
1860      * exchange and can move on to packet discipline.
1861      */
1862     while (1) {
1863         int ret;
1864         if (datalen == 0)
1865             crReturnV;                 /* more data please */
1866         ret = do_ssh_init(*data);
1867         data++;
1868         datalen--;
1869         if (ret == 0)
1870             break;
1871     }
1872
1873     /*
1874      * We emerge from that loop when the initial negotiation is
1875      * over and we have selected an s_rdpkt function. Now pass
1876      * everything to s_rdpkt, and then pass the resulting packets
1877      * to the proper protocol handler.
1878      */
1879     if (datalen == 0)
1880         crReturnV;
1881     while (1) {
1882         while (datalen > 0) {
1883             if (s_rdpkt(&data, &datalen) == 0) {
1884                 if (ssh_state == SSH_STATE_CLOSED) {
1885                     return;
1886                 }
1887                 ssh_protocol(NULL, 0, 1);
1888                 if (ssh_state == SSH_STATE_CLOSED) {
1889                     return;
1890                 }
1891             }
1892         }
1893         crReturnV;
1894     }
1895     crFinishV;
1896 }
1897
1898 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1899                        int calling_back)
1900 {
1901     ssh_state = SSH_STATE_CLOSED;
1902     if (s) {
1903         sk_close(s);
1904         s = NULL;
1905     }
1906     if (error_msg) {
1907         /* A socket error has occurred. */
1908         logevent(error_msg);
1909         connection_fatal(error_msg);
1910     } else {
1911         /* Otherwise, the remote side closed the connection normally. */
1912     }
1913     return 0;
1914 }
1915
1916 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1917 {
1918     ssh_gotdata(data, len);
1919     if (ssh_state == SSH_STATE_CLOSED) {
1920         if (s) {
1921             sk_close(s);
1922             s = NULL;
1923         }
1924         return 0;
1925     }
1926     return 1;
1927 }
1928
1929 static void ssh_sent(Plug plug, int bufsize)
1930 {
1931     /*
1932      * If the send backlog on the SSH socket itself clears, we
1933      * should unthrottle the whole world if it was throttled.
1934      */
1935     if (bufsize < SSH_MAX_BACKLOG)
1936         ssh_throttle_all(0, bufsize);
1937 }
1938
1939 /*
1940  * Connect to specified host and port.
1941  * Returns an error message, or NULL on success.
1942  * Also places the canonical host name into `realhost'. It must be
1943  * freed by the caller.
1944  */
1945 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1946 {
1947     static struct plug_function_table fn_table = {
1948         ssh_closing,
1949         ssh_receive,
1950         ssh_sent,
1951         NULL
1952     }, *fn_table_ptr = &fn_table;
1953
1954     SockAddr addr;
1955     char *err;
1956 #ifdef FWHACK
1957     char *FWhost;
1958     int FWport;
1959 #endif
1960
1961     savedhost = smalloc(1 + strlen(host));
1962     if (!savedhost)
1963         fatalbox("Out of memory");
1964     strcpy(savedhost, host);
1965
1966     if (port < 0)
1967         port = 22;                     /* default ssh port */
1968     savedport = port;
1969
1970 #ifdef FWHACK
1971     FWhost = host;
1972     FWport = port;
1973     host = FWSTR;
1974     port = 23;
1975 #endif
1976
1977     /*
1978      * Try to find host.
1979      */
1980     {
1981         char buf[200];
1982         sprintf(buf, "Looking up host \"%.170s\"", host);
1983         logevent(buf);
1984     }
1985     addr = sk_namelookup(host, realhost);
1986     if ((err = sk_addr_error(addr)))
1987         return err;
1988
1989 #ifdef FWHACK
1990     *realhost = strdup(FWhost);
1991 #endif
1992
1993     /*
1994      * Open socket.
1995      */
1996     {
1997         char buf[200], addrbuf[100];
1998         sk_getaddr(addr, addrbuf, 100);
1999         sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2000         logevent(buf);
2001     }
2002     s = new_connection(addr, *realhost, port, 0, 1, nodelay, &fn_table_ptr);
2003     if ((err = sk_socket_error(s))) {
2004         s = NULL;
2005         return err;
2006     }
2007
2008 #ifdef FWHACK
2009     sk_write(s, "connect ", 8);
2010     sk_write(s, FWhost, strlen(FWhost));
2011     {
2012         char buf[20];
2013         sprintf(buf, " %d\n", FWport);
2014         sk_write(s, buf, strlen(buf));
2015     }
2016 #endif
2017
2018     return NULL;
2019 }
2020
2021 /*
2022  * Throttle or unthrottle the SSH connection.
2023  */
2024 static void ssh1_throttle(int adjust)
2025 {
2026     int old_count = ssh1_throttle_count;
2027     ssh1_throttle_count += adjust;
2028     assert(ssh1_throttle_count >= 0);
2029     if (ssh1_throttle_count && !old_count) {
2030         sk_set_frozen(s, 1);
2031     } else if (!ssh1_throttle_count && old_count) {
2032         sk_set_frozen(s, 0);
2033     }
2034 }
2035
2036 /*
2037  * Throttle or unthrottle _all_ local data streams (for when sends
2038  * on the SSH connection itself back up).
2039  */
2040 static void ssh_throttle_all(int enable, int bufsize)
2041 {
2042     int i;
2043     struct ssh_channel *c;
2044
2045     if (enable == ssh_throttled_all)
2046         return;
2047     ssh_throttled_all = enable;
2048     ssh_overall_bufsize = bufsize;
2049     if (!ssh_channels)
2050         return;
2051     for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
2052         switch (c->type) {
2053           case CHAN_MAINSESSION:
2054             /*
2055              * This is treated separately, outside the switch.
2056              */
2057             break;
2058           case CHAN_X11:
2059             x11_override_throttle(c->u.x11.s, enable);
2060             break;
2061           case CHAN_AGENT:
2062             /* Agent channels require no buffer management. */
2063             break;
2064           case CHAN_SOCKDATA:
2065             pfd_override_throttle(c->u.x11.s, enable);
2066             break;
2067         }
2068     }
2069 }
2070
2071 /*
2072  * Username and password input, abstracted off into reusable
2073  * routines (hopefully even reusable between SSH1 and SSH2!).
2074  */
2075 static char *ssh_userpass_input_buffer;
2076 static int ssh_userpass_input_buflen;
2077 static int ssh_userpass_input_bufpos;
2078 static int ssh_userpass_input_echo;
2079
2080 /* Set up a username or password input loop on a given buffer. */
2081 void setup_userpass_input(char *buffer, int buflen, int echo)
2082 {
2083     ssh_userpass_input_buffer = buffer;
2084     ssh_userpass_input_buflen = buflen;
2085     ssh_userpass_input_bufpos = 0;
2086     ssh_userpass_input_echo = echo;
2087 }
2088
2089 /*
2090  * Process some terminal data in the course of username/password
2091  * input. Returns >0 for success (line of input returned in
2092  * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2093  * for inconclusive (keep waiting for more input please).
2094  */
2095 int process_userpass_input(unsigned char *in, int inlen)
2096 {
2097     char c;
2098
2099     while (inlen--) {
2100         switch (c = *in++) {
2101           case 10:
2102           case 13:
2103             ssh_userpass_input_buffer[ssh_userpass_input_bufpos] = 0;
2104             ssh_userpass_input_buffer[ssh_userpass_input_buflen-1] = 0;
2105             return +1;
2106             break;
2107           case 8:
2108           case 127:
2109             if (ssh_userpass_input_bufpos > 0) {
2110                 if (ssh_userpass_input_echo)
2111                     c_write_str("\b \b");
2112                 ssh_userpass_input_bufpos--;
2113             }
2114             break;
2115           case 21:
2116           case 27:
2117             while (ssh_userpass_input_bufpos > 0) {
2118                 if (ssh_userpass_input_echo)
2119                     c_write_str("\b \b");
2120                 ssh_userpass_input_bufpos--;
2121             }
2122             break;
2123           case 3:
2124           case 4:
2125             return -1;
2126             break;
2127           default:
2128             if (((c >= ' ' && c <= '~') ||
2129                  ((unsigned char) c >= 160))
2130                 && ssh_userpass_input_bufpos < ssh_userpass_input_buflen-1) {
2131                 ssh_userpass_input_buffer[ssh_userpass_input_bufpos++] = c;
2132                 if (ssh_userpass_input_echo)
2133                     c_write(&c, 1);
2134             }
2135             break;
2136         }
2137     }
2138     return 0;
2139 }
2140
2141 /*
2142  * Handle the key exchange and user authentication phases.
2143  */
2144 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
2145 {
2146     int i, j;
2147     static int len;
2148     static unsigned char *rsabuf, *keystr1, *keystr2;
2149     unsigned char cookie[8];
2150     struct RSAKey servkey, hostkey;
2151     struct MD5Context md5c;
2152     static unsigned long supported_ciphers_mask, supported_auths_mask;
2153     static int tried_publickey, tried_agent;
2154     static int tis_auth_refused, ccard_auth_refused;
2155     static unsigned char session_id[16];
2156     static int cipher_type;
2157     static char username[100];
2158     static void *publickey_blob;
2159     int publickey_bloblen;
2160
2161     crBegin;
2162
2163     if (!ispkt)
2164         crWaitUntil(ispkt);
2165
2166     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2167         bombout(("Public key packet not received"));
2168         crReturn(0);
2169     }
2170
2171     logevent("Received public keys");
2172
2173     memcpy(cookie, pktin.body, 8);
2174
2175     i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
2176     j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
2177
2178     /*
2179      * Log the host key fingerprint.
2180      */
2181     {
2182         char logmsg[80];
2183         logevent("Host key fingerprint is:");
2184         strcpy(logmsg, "      ");
2185         hostkey.comment = NULL;
2186         rsa_fingerprint(logmsg + strlen(logmsg),
2187                         sizeof(logmsg) - strlen(logmsg), &hostkey);
2188         logevent(logmsg);
2189     }
2190
2191     ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
2192     supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
2193     supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
2194
2195     ssh1_local_protoflags =
2196         ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2197     ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2198
2199     MD5Init(&md5c);
2200     MD5Update(&md5c, keystr2, hostkey.bytes);
2201     MD5Update(&md5c, keystr1, servkey.bytes);
2202     MD5Update(&md5c, pktin.body, 8);
2203     MD5Final(session_id, &md5c);
2204
2205     for (i = 0; i < 32; i++)
2206         session_key[i] = random_byte();
2207
2208     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2209
2210     rsabuf = smalloc(len);
2211     if (!rsabuf)
2212         fatalbox("Out of memory");
2213
2214     /*
2215      * Verify the host key.
2216      */
2217     {
2218         /*
2219          * First format the key into a string.
2220          */
2221         int len = rsastr_len(&hostkey);
2222         char fingerprint[100];
2223         char *keystr = smalloc(len);
2224         if (!keystr)
2225             fatalbox("Out of memory");
2226         rsastr_fmt(keystr, &hostkey);
2227         rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2228         verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2229                             fingerprint);
2230         sfree(keystr);
2231     }
2232
2233     for (i = 0; i < 32; i++) {
2234         rsabuf[i] = session_key[i];
2235         if (i < 16)
2236             rsabuf[i] ^= session_id[i];
2237     }
2238
2239     if (hostkey.bytes > servkey.bytes) {
2240         rsaencrypt(rsabuf, 32, &servkey);
2241         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2242     } else {
2243         rsaencrypt(rsabuf, 32, &hostkey);
2244         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2245     }
2246
2247     logevent("Encrypted session key");
2248
2249     {
2250         int cipher_chosen = 0, warn = 0;
2251         char *cipher_string = NULL;
2252         for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2253             int next_cipher = cfg.ssh_cipherlist[i];
2254             if (next_cipher == CIPHER_WARN) {
2255                 /* If/when we choose a cipher, warn about it */
2256                 warn = 1;
2257             } else if (next_cipher == CIPHER_AES) {
2258                 /* XXX Probably don't need to mention this. */
2259                 logevent("AES not supported in SSH1, skipping");
2260             } else {
2261                 switch (next_cipher) {
2262                   case CIPHER_3DES:     cipher_type = SSH_CIPHER_3DES;
2263                                         cipher_string = "3DES"; break;
2264                   case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2265                                         cipher_string = "Blowfish"; break;
2266                   case CIPHER_DES:      cipher_type = SSH_CIPHER_DES;
2267                                         cipher_string = "single-DES"; break;
2268                 }
2269                 if (supported_ciphers_mask & (1 << cipher_type))
2270                     cipher_chosen = 1;
2271             }
2272         }
2273         if (!cipher_chosen) {
2274             if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2275                 bombout(("Server violates SSH 1 protocol by not "
2276                          "supporting 3DES encryption"));
2277             else
2278                 /* shouldn't happen */
2279                 bombout(("No supported ciphers found"));
2280             crReturn(0);
2281         }
2282
2283         /* Warn about chosen cipher if necessary. */
2284         if (warn)
2285             askcipher(cipher_string, 0);
2286     }
2287
2288     switch (cipher_type) {
2289       case SSH_CIPHER_3DES:
2290         logevent("Using 3DES encryption");
2291         break;
2292       case SSH_CIPHER_DES:
2293         logevent("Using single-DES encryption");
2294         break;
2295       case SSH_CIPHER_BLOWFISH:
2296         logevent("Using Blowfish encryption");
2297         break;
2298     }
2299
2300     send_packet(SSH1_CMSG_SESSION_KEY,
2301                 PKT_CHAR, cipher_type,
2302                 PKT_DATA, cookie, 8,
2303                 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2304                 PKT_DATA, rsabuf, len,
2305                 PKT_INT, ssh1_local_protoflags, PKT_END);
2306
2307     logevent("Trying to enable encryption...");
2308
2309     sfree(rsabuf);
2310
2311     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2312         cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2313     cipher->sesskey(session_key);
2314
2315     crWaitUntil(ispkt);
2316
2317     if (pktin.type != SSH1_SMSG_SUCCESS) {
2318         bombout(("Encryption not successfully enabled"));
2319         crReturn(0);
2320     }
2321
2322     logevent("Successfully started encryption");
2323
2324     fflush(stdout);
2325     {
2326         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2327             if (ssh_get_line && !ssh_getline_pw_only) {
2328                 if (!ssh_get_line("login as: ",
2329                                   username, sizeof(username), FALSE)) {
2330                     /*
2331                      * get_line failed to get a username.
2332                      * Terminate.
2333                      */
2334                     logevent("No username provided. Abandoning session.");
2335                     ssh_state = SSH_STATE_CLOSED;
2336                     crReturn(1);
2337                 }
2338             } else {
2339                 static int ret;
2340                 c_write_str("login as: ");
2341                 ssh_send_ok = 1;
2342
2343                 setup_userpass_input(username, sizeof(username), 1);
2344                 do {
2345                     crWaitUntil(!ispkt);
2346                     ret = process_userpass_input(in, inlen);
2347                 } while (ret == 0);
2348                 if (ret < 0)
2349                     cleanup_exit(0);
2350                 c_write_str("\r\n");
2351             }
2352         } else {
2353             strncpy(username, cfg.username, 99);
2354             username[99] = '\0';
2355         }
2356
2357         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2358         {
2359             char userlog[22 + sizeof(username)];
2360             sprintf(userlog, "Sent username \"%s\"", username);
2361             logevent(userlog);
2362             if (flags & FLAG_INTERACTIVE &&
2363                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2364                 strcat(userlog, "\r\n");
2365                 c_write_str(userlog);
2366             }
2367         }
2368     }
2369
2370     crWaitUntil(ispkt);
2371
2372     if ((ssh_remote_bugs & BUG_CHOKES_ON_RSA)) {
2373         /* We must not attempt PK auth. Pretend we've already tried it. */
2374         tried_publickey = tried_agent = 1;
2375     } else {
2376         tried_publickey = tried_agent = 0;
2377     }
2378     tis_auth_refused = ccard_auth_refused = 0;
2379     /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2380     if (*cfg.keyfile) {
2381         if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2382             publickey_blob = NULL;
2383     } else
2384         publickey_blob = NULL;
2385
2386     while (pktin.type == SSH1_SMSG_FAILURE) {
2387         static char password[100];
2388         static char prompt[200];
2389         static int pos;
2390         static char c;
2391         static int pwpkt_type;
2392         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2393
2394         if (agent_exists() && !tried_agent) {
2395             /*
2396              * Attempt RSA authentication using Pageant.
2397              */
2398             static unsigned char request[5], *response, *p;
2399             static int responselen;
2400             static int i, nkeys;
2401             static int authed = FALSE;
2402             void *r;
2403
2404             tried_agent = 1;
2405             logevent("Pageant is running. Requesting keys.");
2406
2407             /* Request the keys held by the agent. */
2408             PUT_32BIT(request, 1);
2409             request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2410             agent_query(request, 5, &r, &responselen);
2411             response = (unsigned char *) r;
2412             if (response && responselen >= 5 &&
2413                 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2414                 p = response + 5;
2415                 nkeys = GET_32BIT(p);
2416                 p += 4;
2417                 {
2418                     char buf[64];
2419                     sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2420                     logevent(buf);
2421                 }
2422                 for (i = 0; i < nkeys; i++) {
2423                     static struct RSAKey key;
2424                     static Bignum challenge;
2425                     static char *commentp;
2426                     static int commentlen;
2427
2428                     {
2429                         char buf[64];
2430                         sprintf(buf, "Trying Pageant key #%d", i);
2431                         logevent(buf);
2432                     }
2433                     if (publickey_blob &&
2434                         !memcmp(p, publickey_blob, publickey_bloblen)) {
2435                         logevent("This key matches configured key file");
2436                         tried_publickey = 1;
2437                     }
2438                     p += 4;
2439                     p += ssh1_read_bignum(p, &key.exponent);
2440                     p += ssh1_read_bignum(p, &key.modulus);
2441                     commentlen = GET_32BIT(p);
2442                     p += 4;
2443                     commentp = p;
2444                     p += commentlen;
2445                     send_packet(SSH1_CMSG_AUTH_RSA,
2446                                 PKT_BIGNUM, key.modulus, PKT_END);
2447                     crWaitUntil(ispkt);
2448                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2449                         logevent("Key refused");
2450                         continue;
2451                     }
2452                     logevent("Received RSA challenge");
2453                     ssh1_read_bignum(pktin.body, &challenge);
2454                     {
2455                         char *agentreq, *q, *ret;
2456                         void *vret;
2457                         int len, retlen;
2458                         len = 1 + 4;   /* message type, bit count */
2459                         len += ssh1_bignum_length(key.exponent);
2460                         len += ssh1_bignum_length(key.modulus);
2461                         len += ssh1_bignum_length(challenge);
2462                         len += 16;     /* session id */
2463                         len += 4;      /* response format */
2464                         agentreq = smalloc(4 + len);
2465                         PUT_32BIT(agentreq, len);
2466                         q = agentreq + 4;
2467                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2468                         PUT_32BIT(q, bignum_bitcount(key.modulus));
2469                         q += 4;
2470                         q += ssh1_write_bignum(q, key.exponent);
2471                         q += ssh1_write_bignum(q, key.modulus);
2472                         q += ssh1_write_bignum(q, challenge);
2473                         memcpy(q, session_id, 16);
2474                         q += 16;
2475                         PUT_32BIT(q, 1);        /* response format */
2476                         agent_query(agentreq, len + 4, &vret, &retlen);
2477                         ret = vret;
2478                         sfree(agentreq);
2479                         if (ret) {
2480                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2481                                 logevent("Sending Pageant's response");
2482                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2483                                             PKT_DATA, ret + 5, 16,
2484                                             PKT_END);
2485                                 sfree(ret);
2486                                 crWaitUntil(ispkt);
2487                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
2488                                     logevent
2489                                         ("Pageant's response accepted");
2490                                     if (flags & FLAG_VERBOSE) {
2491                                         c_write_str
2492                                             ("Authenticated using RSA key \"");
2493                                         c_write(commentp, commentlen);
2494                                         c_write_str("\" from agent\r\n");
2495                                     }
2496                                     authed = TRUE;
2497                                 } else
2498                                     logevent
2499                                         ("Pageant's response not accepted");
2500                             } else {
2501                                 logevent
2502                                     ("Pageant failed to answer challenge");
2503                                 sfree(ret);
2504                             }
2505                         } else {
2506                             logevent("No reply received from Pageant");
2507                         }
2508                     }
2509                     freebn(key.exponent);
2510                     freebn(key.modulus);
2511                     freebn(challenge);
2512                     if (authed)
2513                         break;
2514                 }
2515             }
2516             if (authed)
2517                 break;
2518         }
2519         if (*cfg.keyfile && !tried_publickey)
2520             pwpkt_type = SSH1_CMSG_AUTH_RSA;
2521
2522         if (cfg.try_tis_auth &&
2523             (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2524             !tis_auth_refused) {
2525             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2526             logevent("Requested TIS authentication");
2527             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2528             crWaitUntil(ispkt);
2529             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2530                 logevent("TIS authentication declined");
2531                 if (flags & FLAG_INTERACTIVE)
2532                     c_write_str("TIS authentication refused.\r\n");
2533                 tis_auth_refused = 1;
2534                 continue;
2535             } else {
2536                 int challengelen = ((pktin.body[0] << 24) |
2537                                     (pktin.body[1] << 16) |
2538                                     (pktin.body[2] << 8) |
2539                                     (pktin.body[3]));
2540                 logevent("Received TIS challenge");
2541                 if (challengelen > sizeof(prompt) - 1)
2542                     challengelen = sizeof(prompt) - 1;  /* prevent overrun */
2543                 memcpy(prompt, pktin.body + 4, challengelen);
2544                 /* Prompt heuristic comes from OpenSSH */
2545                 strncpy(prompt + challengelen,
2546                         memchr(prompt, '\n', challengelen) ?
2547                         "": "\r\nResponse: ",
2548                         (sizeof prompt) - challengelen);
2549                 prompt[(sizeof prompt) - 1] = '\0';
2550             }
2551         }
2552         if (cfg.try_tis_auth &&
2553             (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2554             !ccard_auth_refused) {
2555             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2556             logevent("Requested CryptoCard authentication");
2557             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2558             crWaitUntil(ispkt);
2559             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2560                 logevent("CryptoCard authentication declined");
2561                 c_write_str("CryptoCard authentication refused.\r\n");
2562                 ccard_auth_refused = 1;
2563                 continue;
2564             } else {
2565                 int challengelen = ((pktin.body[0] << 24) |
2566                                     (pktin.body[1] << 16) |
2567                                     (pktin.body[2] << 8) |
2568                                     (pktin.body[3]));
2569                 logevent("Received CryptoCard challenge");
2570                 if (challengelen > sizeof(prompt) - 1)
2571                     challengelen = sizeof(prompt) - 1;  /* prevent overrun */
2572                 memcpy(prompt, pktin.body + 4, challengelen);
2573                 strncpy(prompt + challengelen,
2574                         memchr(prompt, '\n', challengelen) ?
2575                         "" : "\r\nResponse: ",
2576                         sizeof(prompt) - challengelen);
2577                 prompt[sizeof(prompt) - 1] = '\0';
2578             }
2579         }
2580         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2581             sprintf(prompt, "%.90s@%.90s's password: ",
2582                     username, savedhost);
2583         }
2584         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2585             char *comment = NULL;
2586             int type;
2587             char msgbuf[256];
2588             if (flags & FLAG_VERBOSE)
2589                 c_write_str("Trying public key authentication.\r\n");
2590             sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2591             logevent(msgbuf);
2592             type = key_type(cfg.keyfile);
2593             if (type != SSH_KEYTYPE_SSH1) {
2594                 sprintf(msgbuf, "Key is of wrong type (%s)",
2595                         key_type_to_str(type));
2596                 logevent(msgbuf);
2597                 c_write_str(msgbuf);
2598                 c_write_str("\r\n");
2599                 tried_publickey = 1;
2600                 continue;
2601             }
2602             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2603                 if (flags & FLAG_VERBOSE)
2604                     c_write_str("No passphrase required.\r\n");
2605                 goto tryauth;
2606             }
2607             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2608             sfree(comment);
2609         }
2610
2611         /*
2612          * Show password prompt, having first obtained it via a TIS
2613          * or CryptoCard exchange if we're doing TIS or CryptoCard
2614          * authentication.
2615          */
2616         if (ssh_get_line) {
2617             if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2618                 /*
2619                  * get_line failed to get a password (for example
2620                  * because one was supplied on the command line
2621                  * which has already failed to work). Terminate.
2622                  */
2623                 send_packet(SSH1_MSG_DISCONNECT,
2624                             PKT_STR, "No more passwords available to try",
2625                             PKT_END);
2626                 logevent("Unable to authenticate");
2627                 connection_fatal("Unable to authenticate");
2628                 ssh_state = SSH_STATE_CLOSED;
2629                 crReturn(1);
2630             }
2631         } else {
2632             /* Prompt may have come from server. We've munged it a bit, so
2633              * we know it to be zero-terminated at least once. */
2634             static int ret;
2635             c_write_untrusted(prompt, strlen(prompt));
2636             pos = 0;
2637
2638             setup_userpass_input(password, sizeof(password), 0);
2639             do {
2640                 crWaitUntil(!ispkt);
2641                 ret = process_userpass_input(in, inlen);
2642             } while (ret == 0);
2643             if (ret < 0)
2644                 cleanup_exit(0);
2645             c_write_str("\r\n");
2646         }
2647
2648       tryauth:
2649         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2650             /*
2651              * Try public key authentication with the specified
2652              * key file.
2653              */
2654             static struct RSAKey pubkey;
2655             static Bignum challenge, response;
2656             static int i;
2657             static unsigned char buffer[32];
2658
2659             tried_publickey = 1;
2660             i = loadrsakey(cfg.keyfile, &pubkey, password);
2661             if (i == 0) {
2662                 c_write_str("Couldn't load private key from ");
2663                 c_write_str(cfg.keyfile);
2664                 c_write_str(".\r\n");
2665                 continue;              /* go and try password */
2666             }
2667             if (i == -1) {
2668                 c_write_str("Wrong passphrase.\r\n");
2669                 tried_publickey = 0;
2670                 continue;              /* try again */
2671             }
2672
2673             /*
2674              * Send a public key attempt.
2675              */
2676             send_packet(SSH1_CMSG_AUTH_RSA,
2677                         PKT_BIGNUM, pubkey.modulus, PKT_END);
2678
2679             crWaitUntil(ispkt);
2680             if (pktin.type == SSH1_SMSG_FAILURE) {
2681                 c_write_str("Server refused our public key.\r\n");
2682                 continue;              /* go and try password */
2683             }
2684             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2685                 bombout(("Bizarre response to offer of public key"));
2686                 crReturn(0);
2687             }
2688             ssh1_read_bignum(pktin.body, &challenge);
2689             response = rsadecrypt(challenge, &pubkey);
2690             freebn(pubkey.private_exponent);    /* burn the evidence */
2691
2692             for (i = 0; i < 32; i++) {
2693                 buffer[i] = bignum_byte(response, 31 - i);
2694             }
2695
2696             MD5Init(&md5c);
2697             MD5Update(&md5c, buffer, 32);
2698             MD5Update(&md5c, session_id, 16);
2699             MD5Final(buffer, &md5c);
2700
2701             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2702                         PKT_DATA, buffer, 16, PKT_END);
2703
2704             crWaitUntil(ispkt);
2705             if (pktin.type == SSH1_SMSG_FAILURE) {
2706                 if (flags & FLAG_VERBOSE)
2707                     c_write_str
2708                         ("Failed to authenticate with our public key.\r\n");
2709                 continue;              /* go and try password */
2710             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2711                 bombout(
2712                         ("Bizarre response to RSA authentication response"));
2713                 crReturn(0);
2714             }
2715
2716             break;                     /* we're through! */
2717         } else {
2718             if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2719                 /*
2720                  * Defence against traffic analysis: we send a
2721                  * whole bunch of packets containing strings of
2722                  * different lengths. One of these strings is the
2723                  * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2724                  * The others are all random data in
2725                  * SSH1_MSG_IGNORE packets. This way a passive
2726                  * listener can't tell which is the password, and
2727                  * hence can't deduce the password length.
2728                  * 
2729                  * Anybody with a password length greater than 16
2730                  * bytes is going to have enough entropy in their
2731                  * password that a listener won't find it _that_
2732                  * much help to know how long it is. So what we'll
2733                  * do is:
2734                  * 
2735                  *  - if password length < 16, we send 15 packets
2736                  *    containing string lengths 1 through 15
2737                  * 
2738                  *  - otherwise, we let N be the nearest multiple
2739                  *    of 8 below the password length, and send 8
2740                  *    packets containing string lengths N through
2741                  *    N+7. This won't obscure the order of
2742                  *    magnitude of the password length, but it will
2743                  *    introduce a bit of extra uncertainty.
2744                  * 
2745                  * A few servers (the old 1.2.18 through 1.2.22)
2746                  * can't deal with SSH1_MSG_IGNORE. For these
2747                  * servers, we need an alternative defence. We make
2748                  * use of the fact that the password is interpreted
2749                  * as a C string: so we can append a NUL, then some
2750                  * random data.
2751                  * 
2752                  * One server (a Cisco one) can deal with neither
2753                  * SSH1_MSG_IGNORE _nor_ a padded password string.
2754                  * For this server we are left with no defences
2755                  * against password length sniffing.
2756                  */
2757                 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2758                     /*
2759                      * The server can deal with SSH1_MSG_IGNORE, so
2760                      * we can use the primary defence.
2761                      */
2762                     int bottom, top, pwlen, i;
2763                     char *randomstr;
2764
2765                     pwlen = strlen(password);
2766                     if (pwlen < 16) {
2767                         bottom = 0;    /* zero length passwords are OK! :-) */
2768                         top = 15;
2769                     } else {
2770                         bottom = pwlen & ~7;
2771                         top = bottom + 7;
2772                     }
2773
2774                     assert(pwlen >= bottom && pwlen <= top);
2775
2776                     randomstr = smalloc(top + 1);
2777
2778                     for (i = bottom; i <= top; i++) {
2779                         if (i == pwlen)
2780                             defer_packet(pwpkt_type, PKT_STR, password,
2781                                          PKT_END);
2782                         else {
2783                             for (j = 0; j < i; j++) {
2784                                 do {
2785                                     randomstr[j] = random_byte();
2786                                 } while (randomstr[j] == '\0');
2787                             }
2788                             randomstr[i] = '\0';
2789                             defer_packet(SSH1_MSG_IGNORE,
2790                                          PKT_STR, randomstr, PKT_END);
2791                         }
2792                     }
2793                     logevent("Sending password with camouflage packets");
2794                     ssh_pkt_defersend();
2795                 } 
2796                 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2797                     /*
2798                      * The server can't deal with SSH1_MSG_IGNORE
2799                      * but can deal with padded passwords, so we
2800                      * can use the secondary defence.
2801                      */
2802                     char string[64];
2803                     char *s;
2804                     int len;
2805
2806                     len = strlen(password);
2807                     if (len < sizeof(string)) {
2808                         s = string;
2809                         strcpy(string, password);
2810                         len++;         /* cover the zero byte */
2811                         while (len < sizeof(string)) {
2812                             string[len++] = (char) random_byte();
2813                         }
2814                     } else {
2815                         s = password;
2816                     }
2817                     logevent("Sending length-padded password");
2818                     send_packet(pwpkt_type, PKT_INT, len,
2819                                 PKT_DATA, s, len, PKT_END);
2820                 } else {
2821                     /*
2822                      * The server has _both_
2823                      * BUG_CHOKES_ON_SSH1_IGNORE and
2824                      * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2825                      * therefore nothing we can do.
2826                      */
2827                     int len;
2828                     len = strlen(password);
2829                     logevent("Sending unpadded password");
2830                     send_packet(pwpkt_type, PKT_INT, len,
2831                                 PKT_DATA, password, len, PKT_END);
2832                 }
2833             } else {
2834                 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2835             }
2836         }
2837         logevent("Sent password");
2838         memset(password, 0, strlen(password));
2839         crWaitUntil(ispkt);
2840         if (pktin.type == SSH1_SMSG_FAILURE) {
2841             if (flags & FLAG_VERBOSE)
2842                 c_write_str("Access denied\r\n");
2843             logevent("Authentication refused");
2844         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2845             logevent("Received disconnect request");
2846             ssh_state = SSH_STATE_CLOSED;
2847             crReturn(1);
2848         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2849             bombout(("Strange packet received, type %d", pktin.type));
2850             crReturn(0);
2851         }
2852     }
2853
2854     logevent("Authentication successful");
2855
2856     crFinish(1);
2857 }
2858
2859 void sshfwd_close(struct ssh_channel *c)
2860 {
2861     if (c && !c->closes) {
2862         /*
2863          * If the channel's remoteid is -1, we have sent
2864          * CHANNEL_OPEN for this channel, but it hasn't even been
2865          * acknowledged by the server. So we must set a close flag
2866          * on it now, and then when the server acks the channel
2867          * open, we can close it then.
2868          */
2869         if (((int)c->remoteid) != -1) {
2870             if (ssh_version == 1) {
2871                 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2872                             PKT_END);
2873             } else {
2874                 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2875                 ssh2_pkt_adduint32(c->remoteid);
2876                 ssh2_pkt_send();
2877             }
2878         }
2879         c->closes = 1;
2880         if (c->type == CHAN_X11) {
2881             c->u.x11.s = NULL;
2882             logevent("Forwarded X11 connection terminated");
2883         } else if (c->type == CHAN_SOCKDATA ||
2884                    c->type == CHAN_SOCKDATA_DORMANT) {
2885             c->u.pfd.s = NULL;
2886             logevent("Forwarded port closed");
2887         }
2888     }
2889 }
2890
2891 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2892 {
2893     if (ssh_version == 1) {
2894         send_packet(SSH1_MSG_CHANNEL_DATA,
2895                     PKT_INT, c->remoteid,
2896                     PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2897         /*
2898          * In SSH1 we can return 0 here - implying that forwarded
2899          * connections are never individually throttled - because
2900          * the only circumstance that can cause throttling will be
2901          * the whole SSH connection backing up, in which case
2902          * _everything_ will be throttled as a whole.
2903          */
2904         return 0;
2905     } else {
2906         ssh2_add_channel_data(c, buf, len);
2907         return ssh2_try_send(c);
2908     }
2909 }
2910
2911 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2912 {
2913     if (ssh_version == 1) {
2914         if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2915             c->v.v1.throttling = 0;
2916             ssh1_throttle(-1);
2917         }
2918     } else {
2919         ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2920     }
2921 }
2922
2923 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2924 {
2925     crBegin;
2926
2927     random_init();
2928
2929     while (!do_ssh1_login(in, inlen, ispkt)) {
2930         crReturnV;
2931     }
2932     if (ssh_state == SSH_STATE_CLOSED)
2933         crReturnV;
2934
2935     if (cfg.agentfwd && agent_exists()) {
2936         logevent("Requesting agent forwarding");
2937         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2938         do {
2939             crReturnV;
2940         } while (!ispkt);
2941         if (pktin.type != SSH1_SMSG_SUCCESS
2942             && pktin.type != SSH1_SMSG_FAILURE) {
2943             bombout(("Protocol confusion"));
2944             crReturnV;
2945         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2946             logevent("Agent forwarding refused");
2947         } else {
2948             logevent("Agent forwarding enabled");
2949             ssh_agentfwd_enabled = TRUE;
2950         }
2951     }
2952
2953     if (cfg.x11_forward) {
2954         char proto[20], data[64];
2955         logevent("Requesting X11 forwarding");
2956         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2957         if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2958             send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2959                         PKT_STR, proto, PKT_STR, data,
2960                         PKT_INT, 0, PKT_END);
2961         } else {
2962             send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2963                         PKT_STR, proto, PKT_STR, data, PKT_END);
2964         }
2965         do {
2966             crReturnV;
2967         } while (!ispkt);
2968         if (pktin.type != SSH1_SMSG_SUCCESS
2969             && pktin.type != SSH1_SMSG_FAILURE) {
2970             bombout(("Protocol confusion"));
2971             crReturnV;
2972         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2973             logevent("X11 forwarding refused");
2974         } else {
2975             logevent("X11 forwarding enabled");
2976             ssh_X11_fwd_enabled = TRUE;
2977         }
2978     }
2979
2980     {
2981         char type;
2982         static char *e;
2983         int n;
2984         int sport,dport,sserv,dserv;
2985         char sports[256], dports[256], host[256];
2986         char buf[1024];
2987         struct servent *se;
2988
2989         ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2990         /* Add port forwardings. */
2991         e = cfg.portfwd;
2992         while (*e) {
2993             type = *e++;
2994             n = 0;
2995             while (*e && *e != '\t')
2996                 sports[n++] = *e++;
2997             sports[n] = 0;
2998             if (*e == '\t')
2999                 e++;
3000             n = 0;
3001             while (*e && *e != ':')
3002                 host[n++] = *e++;
3003             host[n] = 0;
3004             if (*e == ':')
3005                 e++;
3006             n = 0;
3007             while (*e)
3008                 dports[n++] = *e++;
3009             dports[n] = 0;
3010             e++;
3011             dport = atoi(dports);
3012             dserv = 0;
3013             if (dport == 0) {
3014                 dserv = 1;
3015                 se = getservbyname(dports, NULL);
3016                 if (se != NULL) {
3017                     dport = ntohs(se->s_port);
3018                 } else {
3019                     sprintf(buf,
3020                             "Service lookup failed for destination port \"%s\"",
3021                             dports);
3022                     logevent(buf);
3023                 }
3024             }
3025             sport = atoi(sports);
3026             sserv = 0;
3027             if (sport == 0) {
3028                 sserv = 1;
3029                 se = getservbyname(sports, NULL);
3030                 if (se != NULL) {
3031                     sport = ntohs(se->s_port);
3032                 } else {
3033                     sprintf(buf,
3034                             "Service lookup failed for source port \"%s\"",
3035                             sports);
3036                     logevent(buf);
3037                 }
3038             }
3039             if (sport && dport) {
3040                 if (type == 'L') {
3041                     pfd_addforward(host, dport, sport);
3042                     sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3043                             " %s:%.*s%.*s%d%.*s",
3044                             sserv ? strlen(sports) : 0, sports,
3045                             sserv, "(", sport, sserv, ")",
3046                             host,
3047                             dserv ? strlen(dports) : 0, dports,
3048                             dserv, "(", dport, dserv, ")");
3049                     logevent(buf);
3050                 } else {
3051                     struct ssh_rportfwd *pf;
3052                     pf = smalloc(sizeof(*pf));
3053                     strcpy(pf->dhost, host);
3054                     pf->dport = dport;
3055                     if (add234(ssh_rportfwds, pf) != pf) {
3056                         sprintf(buf, 
3057                                 "Duplicate remote port forwarding to %s:%d",
3058                                 host, dport);
3059                         logevent(buf);
3060                         sfree(pf);
3061                     } else {
3062                         sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3063                                 " forward to %s:%.*s%.*s%d%.*s",
3064                             sserv ? strlen(sports) : 0, sports,
3065                             sserv, "(", sport, sserv, ")",
3066                             host,
3067                             dserv ? strlen(dports) : 0, dports,
3068                             dserv, "(", dport, dserv, ")");
3069                         logevent(buf);
3070                         send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
3071                                     PKT_INT, sport,
3072                                     PKT_STR, host,
3073                                     PKT_INT, dport,
3074                                     PKT_END);
3075                         do {
3076                             crReturnV;
3077                         } while (!ispkt);
3078                         if (pktin.type != SSH1_SMSG_SUCCESS
3079                             && pktin.type != SSH1_SMSG_FAILURE) {
3080                             bombout(("Protocol confusion"));
3081                             crReturnV;
3082                         } else if (pktin.type == SSH1_SMSG_FAILURE) {
3083                             c_write_str("Server refused port forwarding\r\n");
3084                             ssh_editing = ssh_echoing = 1;
3085                         }
3086                         logevent("Remote port forwarding enabled");
3087                     }
3088                 }
3089             }
3090         }
3091     }
3092
3093     if (!cfg.nopty) {
3094         send_packet(SSH1_CMSG_REQUEST_PTY,
3095                     PKT_STR, cfg.termtype,
3096                     PKT_INT, rows, PKT_INT, cols,
3097                     PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3098         ssh_state = SSH_STATE_INTERMED;
3099         do {
3100             crReturnV;
3101         } while (!ispkt);
3102         if (pktin.type != SSH1_SMSG_SUCCESS
3103             && pktin.type != SSH1_SMSG_FAILURE) {
3104             bombout(("Protocol confusion"));
3105             crReturnV;
3106         } else if (pktin.type == SSH1_SMSG_FAILURE) {
3107             c_write_str("Server refused to allocate pty\r\n");
3108             ssh_editing = ssh_echoing = 1;
3109         }
3110         logevent("Allocated pty");
3111     } else {
3112         ssh_editing = ssh_echoing = 1;
3113     }
3114
3115     if (cfg.compression) {
3116         send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3117         do {
3118             crReturnV;
3119         } while (!ispkt);
3120         if (pktin.type != SSH1_SMSG_SUCCESS
3121             && pktin.type != SSH1_SMSG_FAILURE) {
3122             bombout(("Protocol confusion"));
3123             crReturnV;
3124         } else if (pktin.type == SSH1_SMSG_FAILURE) {
3125             c_write_str("Server refused to compress\r\n");
3126         }
3127         logevent("Started compression");
3128         ssh1_compressing = TRUE;
3129         zlib_compress_init();
3130         zlib_decompress_init();
3131     }
3132
3133     /*
3134      * Start the shell or command.
3135      * 
3136      * Special case: if the first-choice command is an SSH2
3137      * subsystem (hence not usable here) and the second choice
3138      * exists, we fall straight back to that.
3139      */
3140     {
3141         char *cmd = cfg.remote_cmd_ptr;
3142         
3143         if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3144             cmd = cfg.remote_cmd_ptr2;
3145             ssh_fallback_cmd = TRUE;
3146         }
3147         if (*cmd)
3148             send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3149         else
3150             send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
3151         logevent("Started session");
3152     }
3153
3154     ssh_state = SSH_STATE_SESSION;
3155     if (size_needed)
3156         ssh_size();
3157     if (eof_needed)
3158         ssh_special(TS_EOF);
3159
3160     ldisc_send(NULL, 0, 0);            /* cause ldisc to notice changes */
3161     ssh_send_ok = 1;
3162     ssh_channels = newtree234(ssh_channelcmp);
3163     while (1) {
3164         crReturnV;
3165         if (ispkt) {
3166             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
3167                 pktin.type == SSH1_SMSG_STDERR_DATA) {
3168                 long len = GET_32BIT(pktin.body);
3169                 int bufsize =
3170                     from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
3171                                  pktin.body + 4, len);
3172                 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3173                     ssh1_stdout_throttling = 1;
3174                     ssh1_throttle(+1);
3175                 }
3176             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
3177                 ssh_state = SSH_STATE_CLOSED;
3178                 logevent("Received disconnect request");
3179                 crReturnV;
3180             } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
3181                 /* Remote side is trying to open a channel to talk to our
3182                  * X-Server. Give them back a local channel number. */
3183                 struct ssh_channel *c;
3184
3185                 logevent("Received X11 connect request");
3186                 /* Refuse if X11 forwarding is disabled. */
3187                 if (!ssh_X11_fwd_enabled) {
3188                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3189                                 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3190                     logevent("Rejected X11 connect request");
3191                 } else {
3192                     c = smalloc(sizeof(struct ssh_channel));
3193
3194                     if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3195                         logevent("opening X11 forward connection failed");
3196                         sfree(c);
3197                         send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3198                                     PKT_INT, GET_32BIT(pktin.body),
3199                                     PKT_END);
3200                     } else {
3201                         logevent
3202                             ("opening X11 forward connection succeeded");
3203                         c->remoteid = GET_32BIT(pktin.body);
3204                         c->localid = alloc_channel_id();
3205                         c->closes = 0;
3206                         c->v.v1.throttling = 0;
3207                         c->type = CHAN_X11;     /* identify channel type */
3208                         add234(ssh_channels, c);
3209                         send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3210                                     PKT_INT, c->remoteid, PKT_INT,
3211                                     c->localid, PKT_END);
3212                         logevent("Opened X11 forward channel");
3213                     }
3214                 }
3215             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
3216                 /* Remote side is trying to open a channel to talk to our
3217                  * agent. Give them back a local channel number. */
3218                 struct ssh_channel *c;
3219
3220                 /* Refuse if agent forwarding is disabled. */
3221                 if (!ssh_agentfwd_enabled) {
3222                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3223                                 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3224                 } else {
3225                     c = smalloc(sizeof(struct ssh_channel));
3226                     c->remoteid = GET_32BIT(pktin.body);
3227                     c->localid = alloc_channel_id();
3228                     c->closes = 0;
3229                     c->v.v1.throttling = 0;
3230                     c->type = CHAN_AGENT;       /* identify channel type */
3231                     c->u.a.lensofar = 0;
3232                     add234(ssh_channels, c);
3233                     send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3234                                 PKT_INT, c->remoteid, PKT_INT, c->localid,
3235                                 PKT_END);
3236                 }
3237             } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3238                 /* Remote side is trying to open a channel to talk to a
3239                  * forwarded port. Give them back a local channel number. */
3240                 struct ssh_channel *c;
3241                 struct ssh_rportfwd pf;
3242                 int hostsize, port;
3243                 char host[256], buf[1024];
3244                 char *p, *h, *e;
3245                 c = smalloc(sizeof(struct ssh_channel));
3246
3247                 hostsize = GET_32BIT(pktin.body+4);
3248                 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3249                     if (h+1 < host+sizeof(host))
3250                         *h++ = *p;
3251                     p++;
3252                 }
3253                 *h = 0;
3254                 port = GET_32BIT(p);
3255
3256                 strcpy(pf.dhost, host);
3257                 pf.dport = port;
3258
3259                 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3260                     sprintf(buf, "Rejected remote port open request for %s:%d",
3261                             host, port);
3262                     logevent(buf);
3263                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3264                                 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3265                 } else {
3266                     sprintf(buf, "Received remote port open request for %s:%d",
3267                             host, port);
3268                     logevent(buf);
3269                     e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3270                     if (e != NULL) {
3271                         char buf[256];
3272                         sprintf(buf, "Port open failed: %s", e);
3273                         logevent(buf);
3274                         sfree(c);
3275                         send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3276                                     PKT_INT, GET_32BIT(pktin.body),
3277                                     PKT_END);
3278                     } else {
3279                         c->remoteid = GET_32BIT(pktin.body);
3280                         c->localid = alloc_channel_id();
3281                         c->closes = 0;
3282                         c->v.v1.throttling = 0;
3283                         c->type = CHAN_SOCKDATA;        /* identify channel type */
3284                         add234(ssh_channels, c);
3285                         send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3286                                     PKT_INT, c->remoteid, PKT_INT,
3287                                     c->localid, PKT_END);
3288                         logevent("Forwarded port opened successfully");
3289                     }
3290                 }
3291
3292             } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3293                 unsigned int remoteid = GET_32BIT(pktin.body);
3294                 unsigned int localid = GET_32BIT(pktin.body+4);
3295                 struct ssh_channel *c;
3296
3297                 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3298                 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3299                     c->remoteid = localid;
3300                     c->type = CHAN_SOCKDATA;
3301                     c->v.v1.throttling = 0;
3302                     pfd_confirm(c->u.pfd.s);
3303                 }
3304
3305                 if (c && c->closes) {
3306                     /*
3307                      * We have a pending close on this channel,
3308                      * which we decided on before the server acked
3309                      * the channel open. So now we know the
3310                      * remoteid, we can close it again.
3311                      */
3312                     send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3313                                 PKT_END);
3314                 }
3315
3316             } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3317                 unsigned int remoteid = GET_32BIT(pktin.body);
3318                 unsigned int localid = GET_32BIT(pktin.body+4);
3319                 struct ssh_channel *c;
3320
3321                 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3322                 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3323                     logevent("Forwarded connection refused by server");
3324                     pfd_close(c->u.pfd.s);
3325                     del234(ssh_channels, c);
3326                     sfree(c);
3327                 }
3328
3329             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3330                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3331                 /* Remote side closes a channel. */
3332                 unsigned i = GET_32BIT(pktin.body);
3333                 struct ssh_channel *c;
3334                 c = find234(ssh_channels, &i, ssh_channelfind);
3335                 if (c) {
3336                     int closetype;
3337                     closetype =
3338                         (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3339                     if (!(c->closes & closetype))
3340                         send_packet(pktin.type, PKT_INT, c->remoteid,
3341                                     PKT_END);
3342                     if ((c->closes == 0) && (c->type == CHAN_X11)) {
3343                         logevent("Forwarded X11 connection terminated");
3344                         assert(c->u.x11.s != NULL);
3345                         x11_close(c->u.x11.s);
3346                         c->u.x11.s = NULL;
3347                     }
3348                     if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3349                         logevent("Forwarded port closed");
3350                         assert(c->u.pfd.s != NULL);
3351                         pfd_close(c->u.pfd.s);
3352                         c->u.pfd.s = NULL;
3353                     }
3354                     c->closes |= closetype;
3355                     if (c->closes == 3) {
3356                         del234(ssh_channels, c);
3357                         sfree(c);
3358                     }
3359                 }
3360             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3361                 /* Data sent down one of our channels. */
3362                 int i = GET_32BIT(pktin.body);
3363                 int len = GET_32BIT(pktin.body + 4);
3364                 unsigned char *p = pktin.body + 8;
3365                 struct ssh_channel *c;
3366                 c = find234(ssh_channels, &i, ssh_channelfind);
3367                 if (c) {
3368                     int bufsize;
3369                     switch (c->type) {
3370                       case CHAN_X11:
3371                         bufsize = x11_send(c->u.x11.s, p, len);
3372                         break;
3373                       case CHAN_SOCKDATA:
3374                         bufsize = pfd_send(c->u.pfd.s, p, len);
3375                         break;
3376                       case CHAN_AGENT:
3377                         /* Data for an agent message. Buffer it. */
3378                         while (len > 0) {
3379                             if (c->u.a.lensofar < 4) {
3380                                 int l = min(4 - c->u.a.lensofar, len);
3381                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3382                                        l);
3383                                 p += l;
3384                                 len -= l;
3385                                 c->u.a.lensofar += l;
3386                             }
3387                             if (c->u.a.lensofar == 4) {
3388                                 c->u.a.totallen =
3389                                     4 + GET_32BIT(c->u.a.msglen);
3390                                 c->u.a.message = smalloc(c->u.a.totallen);
3391                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
3392                             }
3393                             if (c->u.a.lensofar >= 4 && len > 0) {
3394                                 int l =
3395                                     min(c->u.a.totallen - c->u.a.lensofar,
3396                                         len);
3397                                 memcpy(c->u.a.message + c->u.a.lensofar, p,
3398                                        l);
3399                                 p += l;
3400                                 len -= l;
3401                                 c->u.a.lensofar += l;
3402                             }
3403                             if (c->u.a.lensofar == c->u.a.totallen) {
3404                                 void *reply, *sentreply;
3405                                 int replylen;
3406                                 agent_query(c->u.a.message,
3407                                             c->u.a.totallen, &reply,
3408                                             &replylen);
3409                                 if (reply)
3410                                     sentreply = reply;
3411                                 else {
3412                                     /* Fake SSH_AGENT_FAILURE. */
3413                                     sentreply = "\0\0\0\1\5";
3414                                     replylen = 5;
3415                                 }
3416                                 send_packet(SSH1_MSG_CHANNEL_DATA,
3417                                             PKT_INT, c->remoteid,
3418                                             PKT_INT, replylen,
3419                                             PKT_DATA, sentreply, replylen,
3420                                             PKT_END);
3421                                 if (reply)
3422                                     sfree(reply);
3423                                 sfree(c->u.a.message);
3424                                 c->u.a.lensofar = 0;
3425                             }
3426                         }
3427                         bufsize = 0;   /* agent channels never back up */
3428                         break;
3429                     }
3430                     if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3431                         c->v.v1.throttling = 1;
3432                         ssh1_throttle(+1);
3433                     }
3434                 }
3435             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3436                 /* may be from EXEC_SHELL on some servers */
3437             } else if (pktin.type == SSH1_SMSG_FAILURE) {
3438                 /* may be from EXEC_SHELL on some servers
3439                  * if no pty is available or in other odd cases. Ignore */
3440             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3441                 char buf[100];
3442                 ssh_exitcode = GET_32BIT(pktin.body);
3443                 sprintf(buf, "Server sent command exit status %d",
3444                         ssh_exitcode);
3445                 logevent(buf);
3446                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3447                 /*
3448                  * In case `helpful' firewalls or proxies tack
3449                  * extra human-readable text on the end of the
3450                  * session which we might mistake for another
3451                  * encrypted packet, we close the session once
3452                  * we've sent EXIT_CONFIRMATION.
3453                  */
3454                 ssh_state = SSH_STATE_CLOSED;
3455                 crReturnV;
3456             } else {
3457                 bombout(("Strange packet received: type %d", pktin.type));
3458                 crReturnV;
3459             }
3460         } else {
3461             while (inlen > 0) {
3462                 int len = min(inlen, 512);
3463                 send_packet(SSH1_CMSG_STDIN_DATA,
3464                             PKT_INT, len, PKT_DATA, in, len, PKT_END);
3465                 in += len;
3466                 inlen -= len;
3467             }
3468         }
3469     }
3470
3471     crFinishV;
3472 }
3473
3474 /*
3475  * Utility routine for decoding comma-separated strings in KEXINIT.
3476  */
3477 static int in_commasep_string(char *needle, char *haystack, int haylen)
3478 {
3479     int needlen = strlen(needle);
3480     while (1) {
3481         /*
3482          * Is it at the start of the string?
3483          */
3484         if (haylen >= needlen &&       /* haystack is long enough */
3485             !memcmp(needle, haystack, needlen) &&       /* initial match */
3486             (haylen == needlen || haystack[needlen] == ',')
3487             /* either , or EOS follows */
3488             )
3489             return 1;
3490         /*
3491          * If not, search for the next comma and resume after that.
3492          * If no comma found, terminate.
3493          */
3494         while (haylen > 0 && *haystack != ',')
3495             haylen--, haystack++;
3496         if (haylen == 0)
3497             return 0;
3498         haylen--, haystack++;          /* skip over comma itself */
3499     }
3500 }
3501
3502 /*
3503  * SSH2 key creation method.
3504  */
3505 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3506                        char *keyspace)
3507 {
3508     SHA_State s;
3509     /* First 20 bytes. */
3510     SHA_Init(&s);
3511     if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3512         sha_mpint(&s, K);
3513     SHA_Bytes(&s, H, 20);
3514     SHA_Bytes(&s, &chr, 1);
3515     SHA_Bytes(&s, sessid, 20);
3516     SHA_Final(&s, keyspace);
3517     /* Next 20 bytes. */
3518     SHA_Init(&s);
3519     if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3520         sha_mpint(&s, K);
3521     SHA_Bytes(&s, H, 20);
3522     SHA_Bytes(&s, keyspace, 20);
3523     SHA_Final(&s, keyspace + 20);
3524 }
3525
3526 /*
3527  * Handle the SSH2 transport layer.
3528  */
3529 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3530 {
3531     static int i, j, len, nbits, pbits, warn;
3532     static char *str;
3533     static Bignum p, g, e, f, K;
3534     static int kex_init_value, kex_reply_value;
3535     static const struct ssh_mac **maclist;
3536     static int nmacs;
3537     static const struct ssh2_cipher *cscipher_tobe = NULL;
3538     static const struct ssh2_cipher *sccipher_tobe = NULL;
3539     static const struct ssh_mac *csmac_tobe = NULL;
3540     static const struct ssh_mac *scmac_tobe = NULL;
3541     static const struct ssh_compress *cscomp_tobe = NULL;
3542     static const struct ssh_compress *sccomp_tobe = NULL;
3543     static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3544     static int hostkeylen, siglen;
3545     static void *hkey;                 /* actual host key */
3546     static unsigned char exchange_hash[20];
3547     static unsigned char keyspace[40];
3548     static int n_preferred_ciphers;
3549     static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3550     static const struct ssh_compress *preferred_comp;
3551     static int cipherstr_started;
3552     static int first_kex;
3553
3554     crBegin;
3555     random_init();
3556     first_kex = 1;
3557
3558     /*
3559      * Set up the preferred ciphers. (NULL => warn below here)
3560      */
3561     n_preferred_ciphers = 0;
3562     for (i = 0; i < CIPHER_MAX; i++) {
3563         switch (cfg.ssh_cipherlist[i]) {
3564           case CIPHER_BLOWFISH:
3565             preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3566             n_preferred_ciphers++;
3567             break;
3568           case CIPHER_DES:
3569             if (cfg.ssh2_des_cbc) {
3570                 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3571                 n_preferred_ciphers++;
3572             }
3573             break;
3574           case CIPHER_3DES:
3575             preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3576             n_preferred_ciphers++;
3577             break;
3578           case CIPHER_AES:
3579             preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3580             n_preferred_ciphers++;
3581             break;
3582           case CIPHER_WARN:
3583             /* Flag for later. Don't bother if it's the last in
3584              * the list. */
3585             if (i < CIPHER_MAX - 1) {
3586                 preferred_ciphers[n_preferred_ciphers] = NULL;
3587                 n_preferred_ciphers++;
3588             }
3589             break;
3590         }
3591     }
3592
3593     /*
3594      * Set up preferred compression.
3595      */
3596     if (cfg.compression)
3597         preferred_comp = &ssh_zlib;
3598     else
3599         preferred_comp = &ssh_comp_none;
3600
3601     /*
3602      * Be prepared to work around the buggy MAC problem.
3603      */
3604     if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3605         maclist = buggymacs, nmacs = lenof(buggymacs);
3606     else
3607         maclist = macs, nmacs = lenof(macs);
3608
3609   begin_key_exchange:
3610     /*
3611      * Construct and send our key exchange packet.
3612      */
3613     ssh2_pkt_init(SSH2_MSG_KEXINIT);
3614     for (i = 0; i < 16; i++)
3615         ssh2_pkt_addbyte((unsigned char) random_byte());
3616     /* List key exchange algorithms. */
3617     ssh2_pkt_addstring_start();
3618     for (i = 0; i < lenof(kex_algs); i++) {
3619         ssh2_pkt_addstring_str(kex_algs[i]->name);
3620         if (i < lenof(kex_algs) - 1)
3621             ssh2_pkt_addstring_str(",");
3622     }
3623     /* List server host key algorithms. */
3624     ssh2_pkt_addstring_start();
3625     for (i = 0; i < lenof(hostkey_algs); i++) {
3626         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3627         if (i < lenof(hostkey_algs) - 1)
3628             ssh2_pkt_addstring_str(",");
3629     }
3630     /* List client->server encryption algorithms. */
3631     ssh2_pkt_addstring_start();
3632     cipherstr_started = 0;
3633     for (i = 0; i < n_preferred_ciphers; i++) {
3634         const struct ssh2_ciphers *c = preferred_ciphers[i];
3635         if (!c) continue;              /* warning flag */
3636         for (j = 0; j < c->nciphers; j++) {
3637             if (cipherstr_started)
3638                 ssh2_pkt_addstring_str(",");
3639             ssh2_pkt_addstring_str(c->list[j]->name);
3640             cipherstr_started = 1;
3641         }
3642     }
3643     /* List server->client encryption algorithms. */
3644     ssh2_pkt_addstring_start();
3645     cipherstr_started = 0;
3646     for (i = 0; i < n_preferred_ciphers; i++) {
3647         const struct ssh2_ciphers *c = preferred_ciphers[i];
3648         if (!c) continue; /* warning flag */
3649         for (j = 0; j < c->nciphers; j++) {
3650             if (cipherstr_started)
3651                 ssh2_pkt_addstring_str(",");
3652             ssh2_pkt_addstring_str(c->list[j]->name);
3653             cipherstr_started = 1;
3654         }
3655     }
3656     /* List client->server MAC algorithms. */
3657     ssh2_pkt_addstring_start();
3658     for (i = 0; i < nmacs; i++) {
3659         ssh2_pkt_addstring_str(maclist[i]->name);
3660         if (i < nmacs - 1)
3661             ssh2_pkt_addstring_str(",");
3662     }
3663     /* List server->client MAC algorithms. */
3664     ssh2_pkt_addstring_start();
3665     for (i = 0; i < nmacs; i++) {
3666         ssh2_pkt_addstring_str(maclist[i]->name);
3667         if (i < nmacs - 1)
3668             ssh2_pkt_addstring_str(",");
3669     }
3670     /* List client->server compression algorithms. */
3671     ssh2_pkt_addstring_start();
3672     for (i = 0; i < lenof(compressions) + 1; i++) {
3673         const struct ssh_compress *c =
3674             i == 0 ? preferred_comp : compressions[i - 1];
3675         ssh2_pkt_addstring_str(c->name);
3676         if (i < lenof(compressions))
3677             ssh2_pkt_addstring_str(",");
3678     }
3679     /* List server->client compression algorithms. */
3680     ssh2_pkt_addstring_start();
3681     for (i = 0; i < lenof(compressions) + 1; i++) {
3682         const struct ssh_compress *c =
3683             i == 0 ? preferred_comp : compressions[i - 1];
3684         ssh2_pkt_addstring_str(c->name);
3685         if (i < lenof(compressions))
3686             ssh2_pkt_addstring_str(",");
3687     }
3688     /* List client->server languages. Empty list. */
3689     ssh2_pkt_addstring_start();
3690     /* List server->client languages. Empty list. */
3691     ssh2_pkt_addstring_start();
3692     /* First KEX packet does _not_ follow, because we're not that brave. */
3693     ssh2_pkt_addbool(FALSE);
3694     /* Reserved. */
3695     ssh2_pkt_adduint32(0);
3696
3697     exhash = exhashbase;
3698     sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3699
3700     ssh2_pkt_send();
3701
3702     if (!ispkt)
3703         crWaitUntil(ispkt);
3704     sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3705
3706     /*
3707      * Now examine the other side's KEXINIT to see what we're up
3708      * to.
3709      */
3710     if (pktin.type != SSH2_MSG_KEXINIT) {
3711         bombout(("expected key exchange packet from server"));
3712         crReturn(0);
3713     }
3714     kex = NULL;
3715     hostkey = NULL;
3716     cscipher_tobe = NULL;
3717     sccipher_tobe = NULL;
3718     csmac_tobe = NULL;
3719     scmac_tobe = NULL;
3720     cscomp_tobe = NULL;
3721     sccomp_tobe = NULL;
3722     pktin.savedpos += 16;              /* skip garbage cookie */
3723     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
3724     for (i = 0; i < lenof(kex_algs); i++) {
3725         if (in_commasep_string(kex_algs[i]->name, str, len)) {
3726             kex = kex_algs[i];
3727             break;
3728         }
3729     }
3730     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
3731     for (i = 0; i < lenof(hostkey_algs); i++) {
3732         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3733             hostkey = hostkey_algs[i];
3734             break;
3735         }
3736     }
3737     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
3738     warn = 0;
3739     for (i = 0; i < n_preferred_ciphers; i++) {
3740         const struct ssh2_ciphers *c = preferred_ciphers[i];
3741         if (!c) {
3742             warn = 1;
3743         } else {
3744             for (j = 0; j < c->nciphers; j++) {
3745                 if (in_commasep_string(c->list[j]->name, str, len)) {
3746                     cscipher_tobe = c->list[j];
3747                     break;
3748                 }
3749             }
3750         }
3751         if (cscipher_tobe) {
3752             if (warn)
3753                 askcipher(cscipher_tobe->name, 1);
3754             break;
3755         }
3756     }
3757     if (!cscipher_tobe) {
3758         bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3759         crReturn(0);
3760     }
3761
3762     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
3763     warn = 0;
3764     for (i = 0; i < n_preferred_ciphers; i++) {
3765         const struct ssh2_ciphers *c = preferred_ciphers[i];
3766         if (!c) {
3767             warn = 1;
3768         } else {
3769             for (j = 0; j < c->nciphers; j++) {
3770                 if (in_commasep_string(c->list[j]->name, str, len)) {
3771                     sccipher_tobe = c->list[j];
3772                     break;
3773                 }
3774             }
3775         }
3776         if (sccipher_tobe) {
3777             if (warn)
3778                 askcipher(sccipher_tobe->name, 2);
3779             break;
3780         }
3781     }
3782     if (!sccipher_tobe) {
3783         bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3784         crReturn(0);
3785     }
3786
3787     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
3788     for (i = 0; i < nmacs; i++) {
3789         if (in_commasep_string(maclist[i]->name, str, len)) {
3790             csmac_tobe = maclist[i];
3791             break;
3792         }
3793     }
3794     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
3795     for (i = 0; i < nmacs; i++) {
3796         if (in_commasep_string(maclist[i]->name, str, len)) {
3797             scmac_tobe = maclist[i];
3798             break;
3799         }
3800     }
3801     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
3802     for (i = 0; i < lenof(compressions) + 1; i++) {
3803         const struct ssh_compress *c =
3804             i == 0 ? preferred_comp : compressions[i - 1];
3805         if (in_commasep_string(c->name, str, len)) {
3806             cscomp_tobe = c;
3807             break;
3808         }
3809     }
3810     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
3811     for (i = 0; i < lenof(compressions) + 1; i++) {
3812         const struct ssh_compress *c =
3813             i == 0 ? preferred_comp : compressions[i - 1];
3814         if (in_commasep_string(c->name, str, len)) {
3815             sccomp_tobe = c;
3816             break;
3817         }
3818     }
3819
3820     /*
3821      * Work out the number of bits of key we will need from the key
3822      * exchange. We start with the maximum key length of either
3823      * cipher...
3824      */
3825     {
3826         int csbits, scbits;
3827
3828         csbits = cscipher_tobe->keylen;
3829         scbits = sccipher_tobe->keylen;
3830         nbits = (csbits > scbits ? csbits : scbits);
3831     }
3832     /* The keys only have 160-bit entropy, since they're based on
3833      * a SHA-1 hash. So cap the key size at 160 bits. */
3834     if (nbits > 160)
3835         nbits = 160;
3836
3837     /*
3838      * If we're doing Diffie-Hellman group exchange, start by
3839      * requesting a group.
3840      */
3841     if (kex == &ssh_diffiehellman_gex) {
3842         logevent("Doing Diffie-Hellman group exchange");
3843         ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3844         /*
3845          * Work out how big a DH group we will need to allow that
3846          * much data.
3847          */
3848         pbits = 512 << ((nbits - 1) / 64);
3849         ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3850         ssh2_pkt_adduint32(pbits);
3851         ssh2_pkt_send();
3852
3853         crWaitUntil(ispkt);
3854         if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3855             bombout(("expected key exchange group packet from server"));
3856             crReturn(0);
3857         }
3858         p = ssh2_pkt_getmp();
3859         g = ssh2_pkt_getmp();
3860         dh_setup_group(p, g);
3861         kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3862         kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3863     } else {
3864         ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3865         dh_setup_group1();
3866         kex_init_value = SSH2_MSG_KEXDH_INIT;
3867         kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3868     }
3869
3870     logevent("Doing Diffie-Hellman key exchange");
3871     /*
3872      * Now generate and send e for Diffie-Hellman.
3873      */
3874     e = dh_create_e(nbits * 2);
3875     ssh2_pkt_init(kex_init_value);
3876     ssh2_pkt_addmp(e);
3877     ssh2_pkt_send();
3878
3879     crWaitUntil(ispkt);
3880     if (pktin.type != kex_reply_value) {
3881         bombout(("expected key exchange reply packet from server"));
3882         crReturn(0);
3883     }
3884     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3885     f = ssh2_pkt_getmp();
3886     ssh2_pkt_getstring(&sigdata, &siglen);
3887
3888     K = dh_find_K(f);
3889
3890     sha_string(&exhash, hostkeydata, hostkeylen);
3891     if (kex == &ssh_diffiehellman_gex) {
3892         sha_uint32(&exhash, pbits);
3893         sha_mpint(&exhash, p);
3894         sha_mpint(&exhash, g);
3895     }
3896     sha_mpint(&exhash, e);
3897     sha_mpint(&exhash, f);
3898     sha_mpint(&exhash, K);
3899     SHA_Final(&exhash, exchange_hash);
3900
3901     dh_cleanup();
3902
3903 #if 0
3904     debug(("Exchange hash is:\n"));
3905     dmemdump(exchange_hash, 20);
3906 #endif
3907
3908     hkey = hostkey->newkey(hostkeydata, hostkeylen);
3909     if (!hkey ||
3910         !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3911         bombout(("Server's host key did not match the signature supplied"));
3912         crReturn(0);
3913     }
3914
3915     /*
3916      * Authenticate remote host: verify host key. (We've already
3917      * checked the signature of the exchange hash.)
3918      */
3919     keystr = hostkey->fmtkey(hkey);
3920     fingerprint = hostkey->fingerprint(hkey);
3921     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3922                         keystr, fingerprint);
3923     if (first_kex) {                   /* don't bother logging this in rekeys */
3924         logevent("Host key fingerprint is:");
3925         logevent(fingerprint);
3926     }
3927     sfree(fingerprint);
3928     sfree(keystr);
3929     hostkey->freekey(hkey);
3930
3931     /*
3932      * Send SSH2_MSG_NEWKEYS.
3933      */
3934     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3935     ssh2_pkt_send();
3936
3937     /*
3938      * Expect SSH2_MSG_NEWKEYS from server.
3939      */
3940     crWaitUntil(ispkt);
3941     if (pktin.type != SSH2_MSG_NEWKEYS) {
3942         bombout(("expected new-keys packet from server"));
3943         crReturn(0);
3944     }
3945
3946     /*
3947      * Create and initialise session keys.
3948      */
3949     cscipher = cscipher_tobe;
3950     sccipher = sccipher_tobe;
3951     csmac = csmac_tobe;
3952     scmac = scmac_tobe;
3953     cscomp = cscomp_tobe;
3954     sccomp = sccomp_tobe;
3955     cscomp->compress_init();
3956     sccomp->decompress_init();
3957     /*
3958      * Set IVs after keys. Here we use the exchange hash from the
3959      * _first_ key exchange.
3960      */
3961     if (first_kex)
3962         memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3963     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3964     cscipher->setcskey(keyspace);
3965     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3966     sccipher->setsckey(keyspace);
3967     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3968     cscipher->setcsiv(keyspace);
3969     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3970     sccipher->setsciv(keyspace);
3971     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3972     csmac->setcskey(keyspace);
3973     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3974     scmac->setsckey(keyspace);
3975
3976     /*
3977      * If this is the first key exchange phase, we must pass the
3978      * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3979      * wants to see it but because it will need time to initialise
3980      * itself before it sees an actual packet. In subsequent key
3981      * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3982      * it would only confuse the layer above.
3983      */
3984     if (!first_kex) {
3985         crReturn(0);
3986     }
3987     first_kex = 0;
3988
3989     /*
3990      * Now we're encrypting. Begin returning 1 to the protocol main
3991      * function so that other things can run on top of the
3992      * transport. If we ever see a KEXINIT, we must go back to the
3993      * start.
3994      */
3995     while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3996         crReturn(1);
3997     }
3998     logevent("Server initiated key re-exchange");
3999     goto begin_key_exchange;
4000
4001     crFinish(1);
4002 }
4003
4004 /*
4005  * Add data to an SSH2 channel output buffer.
4006  */
4007 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4008                                   int len)
4009 {
4010     bufchain_add(&c->v.v2.outbuffer, buf, len);
4011 }
4012
4013 /*
4014  * Attempt to send data on an SSH2 channel.
4015  */
4016 static int ssh2_try_send(struct ssh_channel *c)
4017 {
4018     while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4019         int len;
4020         void *data;
4021         bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4022         if ((unsigned)len > c->v.v2.remwindow)
4023             len = c->v.v2.remwindow;
4024         if ((unsigned)len > c->v.v2.remmaxpkt)
4025             len = c->v.v2.remmaxpkt;
4026         ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4027         ssh2_pkt_adduint32(c->remoteid);
4028         ssh2_pkt_addstring_start();
4029         ssh2_pkt_addstring_data(data, len);
4030         ssh2_pkt_send();
4031         bufchain_consume(&c->v.v2.outbuffer, len);
4032         c->v.v2.remwindow -= len;
4033     }
4034
4035     /*
4036      * After having sent as much data as we can, return the amount
4037      * still buffered.
4038      */
4039     return bufchain_size(&c->v.v2.outbuffer);
4040 }
4041
4042 /*
4043  * Potentially enlarge the window on an SSH2 channel.
4044  */
4045 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4046 {
4047     /*
4048      * Never send WINDOW_ADJUST for a channel that the remote side
4049      * already thinks it's closed; there's no point, since it won't
4050      * be sending any more data anyway.
4051      */
4052     if (c->closes != 0)
4053         return;
4054
4055     if (newwin > c->v.v2.locwindow) {
4056         ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4057         ssh2_pkt_adduint32(c->remoteid);
4058         ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
4059         ssh2_pkt_send();
4060         c->v.v2.locwindow = newwin;
4061     }
4062 }
4063
4064 /*
4065  * Handle the SSH2 userauth and connection layers.
4066  */
4067 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
4068 {
4069     static enum {
4070         AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4071         AUTH_PASSWORD,
4072         AUTH_KEYBOARD_INTERACTIVE
4073     } method;
4074     static enum {
4075         AUTH_TYPE_NONE,
4076         AUTH_TYPE_PUBLICKEY,
4077         AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4078         AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4079         AUTH_TYPE_PASSWORD,
4080         AUTH_TYPE_KEYBOARD_INTERACTIVE,
4081         AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4082     } type;
4083     static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4084     static int tried_pubkey_config, tried_agent, tried_keyb_inter;
4085     static int kbd_inter_running;
4086     static int we_are_in;
4087     static int num_prompts, curr_prompt, echo;
4088     static char username[100];
4089     static int got_username;
4090     static char pwprompt[200];
4091     static char password[100];
4092     static void *publickey_blob;
4093     static int publickey_bloblen;
4094
4095     crBegin;
4096
4097     /*
4098      * Request userauth protocol, and await a response to it.
4099      */
4100     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4101     ssh2_pkt_addstring("ssh-userauth");
4102     ssh2_pkt_send();
4103     crWaitUntilV(ispkt);
4104     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4105         bombout(("Server refused user authentication protocol"));
4106         crReturnV;
4107     }
4108
4109     /*
4110      * We repeat this whole loop, including the username prompt,
4111      * until we manage a successful authentication. If the user
4112      * types the wrong _password_, they are sent back to the
4113      * beginning to try another username. (If they specify a
4114      * username in the config, they are never asked, even if they
4115      * do give a wrong password.)
4116      * 
4117      * I think this best serves the needs of
4118      * 
4119      *  - the people who have no configuration, no keys, and just
4120      *    want to try repeated (username,password) pairs until they
4121      *    type both correctly
4122      * 
4123      *  - people who have keys and configuration but occasionally
4124      *    need to fall back to passwords
4125      * 
4126      *  - people with a key held in Pageant, who might not have
4127      *    logged in to a particular machine before; so they want to
4128      *    type a username, and then _either_ their key will be
4129      *    accepted, _or_ they will type a password. If they mistype
4130      *    the username they will want to be able to get back and
4131      *    retype it!
4132      */
4133     username[0] = '\0';
4134     got_username = FALSE;
4135     do {
4136         /*
4137          * Get a username.
4138          */
4139         if (got_username && !cfg.change_username) {
4140             /*
4141              * We got a username last time round this loop, and
4142              * with change_username turned off we don't try to get
4143              * it again.
4144              */
4145         } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4146             if (ssh_get_line && !ssh_getline_pw_only) {
4147                 if (!ssh_get_line("login as: ",
4148                                   username, sizeof(username), FALSE)) {
4149                     /*
4150                      * get_line failed to get a username.
4151                      * Terminate.
4152                      */
4153                     logevent("No username provided. Abandoning session.");
4154                     ssh_state = SSH_STATE_CLOSED;
4155                     crReturnV;
4156                 }
4157             } else {
4158                 static int ret;
4159                 c_write_str("login as: ");
4160                 ssh_send_ok = 1;
4161                 setup_userpass_input(username, sizeof(username), 1);
4162                 do {
4163                     crWaitUntilV(!ispkt);
4164                     ret = process_userpass_input(in, inlen);
4165                 } while (ret == 0);
4166                 if (ret < 0)
4167                     cleanup_exit(0);
4168             }
4169             c_write_str("\r\n");
4170             username[strcspn(username, "\n\r")] = '\0';
4171         } else {
4172             char stuff[200];
4173             strncpy(username, cfg.username, 99);
4174             username[99] = '\0';
4175             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4176                 sprintf(stuff, "Using username \"%s\".\r\n", username);
4177                 c_write_str(stuff);
4178             }
4179         }
4180         got_username = TRUE;
4181
4182         /*
4183          * Send an authentication request using method "none": (a)
4184          * just in case it succeeds, and (b) so that we know what
4185          * authentication methods we can usefully try next.
4186          */
4187         ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4188
4189         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4190         ssh2_pkt_addstring(username);
4191         ssh2_pkt_addstring("ssh-connection");   /* service requested */
4192         ssh2_pkt_addstring("none");    /* method */
4193         ssh2_pkt_send();
4194         type = AUTH_TYPE_NONE;
4195         gotit = FALSE;
4196         we_are_in = FALSE;
4197
4198         tried_pubkey_config = FALSE;
4199         tried_agent = FALSE;
4200         tried_keyb_inter = FALSE;
4201         kbd_inter_running = FALSE;
4202         /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4203         if (*cfg.keyfile) {
4204             int keytype;
4205             logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4206             keytype = key_type(cfg.keyfile);
4207             if (keytype == SSH_KEYTYPE_SSH2)
4208                 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4209                                                       &publickey_bloblen);
4210             else {
4211                 char msgbuf[256];
4212                 logeventf("Unable to use this key file (%s)",
4213                         key_type_to_str(keytype));
4214                 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4215                         cfg.keyfile, key_type_to_str(keytype));
4216                 c_write_str(msgbuf);
4217                 publickey_blob = NULL;
4218             }
4219         } else
4220             publickey_blob = NULL;
4221
4222         while (1) {
4223             /*
4224              * Wait for the result of the last authentication request.
4225              */
4226             if (!gotit)
4227                 crWaitUntilV(ispkt);
4228             while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4229                 char *banner;
4230                 int size;
4231                 /*
4232                  * Don't show the banner if we're operating in
4233                  * non-verbose non-interactive mode. (It's probably
4234                  * a script, which means nobody will read the
4235                  * banner _anyway_, and moreover the printing of
4236                  * the banner will screw up processing on the
4237                  * output of (say) plink.)
4238                  */
4239                 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4240                     ssh2_pkt_getstring(&banner, &size);
4241                     if (banner)
4242                         c_write_untrusted(banner, size);
4243                 }
4244                 crWaitUntilV(ispkt);
4245             }
4246             if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4247                 logevent("Access granted");
4248                 we_are_in = TRUE;
4249                 break;
4250             }
4251
4252             if (kbd_inter_running &&
4253                 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4254                 /*
4255                  * This is either a further set-of-prompts packet
4256                  * in keyboard-interactive authentication, or it's
4257                  * the same one and we came back here with `gotit'
4258                  * set. In the former case, we must reset the
4259                  * curr_prompt variable.
4260                  */
4261                 if (!gotit)
4262                     curr_prompt = 0;
4263             } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4264                 bombout(("Strange packet received during authentication: type %d",
4265                          pktin.type));
4266                 crReturnV;
4267             }
4268
4269             gotit = FALSE;
4270
4271             /*
4272              * OK, we're now sitting on a USERAUTH_FAILURE message, so
4273              * we can look at the string in it and know what we can
4274              * helpfully try next.
4275              */
4276             if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4277                 char *methods;
4278                 int methlen;
4279                 ssh2_pkt_getstring(&methods, &methlen);
4280                 kbd_inter_running = FALSE;
4281                 if (!ssh2_pkt_getbool()) {
4282                     /*
4283                      * We have received an unequivocal Access
4284                      * Denied. This can translate to a variety of
4285                      * messages:
4286                      * 
4287                      *  - if we'd just tried "none" authentication,
4288                      *    it's not worth printing anything at all
4289                      * 
4290                      *  - if we'd just tried a public key _offer_,
4291                      *    the message should be "Server refused our
4292                      *    key" (or no message at all if the key
4293                      *    came from Pageant)
4294                      * 
4295                      *  - if we'd just tried anything else, the
4296                      *    message really should be "Access denied".
4297                      * 
4298                      * Additionally, if we'd just tried password
4299                      * authentication, we should break out of this
4300                      * whole loop so as to go back to the username
4301                      * prompt.
4302                      */
4303                     if (type == AUTH_TYPE_NONE) {
4304                         /* do nothing */
4305                     } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4306                                type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4307                         if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4308                             c_write_str("Server refused our key\r\n");
4309                         logevent("Server refused public key");
4310                     } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4311                         /* server declined keyboard-interactive; ignore */
4312                     } else {
4313                         c_write_str("Access denied\r\n");
4314                         logevent("Access denied");
4315                         if (type == AUTH_TYPE_PASSWORD) {
4316                             we_are_in = FALSE;
4317                             break;
4318                         }
4319                     }
4320                 } else {
4321                     c_write_str("Further authentication required\r\n");
4322                     logevent("Further authentication required");
4323                 }
4324
4325                 can_pubkey =
4326                     in_commasep_string("publickey", methods, methlen);
4327                 can_passwd =
4328                     in_commasep_string("password", methods, methlen);
4329                 can_keyb_inter = cfg.try_ki_auth &&
4330                     in_commasep_string("keyboard-interactive", methods, methlen);
4331             }
4332
4333             method = 0;
4334             ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4335
4336             /*
4337              * Most password/passphrase prompts will be
4338              * non-echoing, so we set this to 0 by default.
4339              * Exception is that some keyboard-interactive prompts
4340              * can be echoing, in which case we'll set this to 1.
4341              */
4342             echo = 0;
4343
4344             if (!method && can_pubkey && agent_exists() && !tried_agent) {
4345                 /*
4346                  * Attempt public-key authentication using Pageant.
4347                  */
4348                 static unsigned char request[5], *response, *p;
4349                 static int responselen;
4350                 static int i, nkeys;
4351                 static int authed = FALSE;
4352                 void *r;
4353
4354                 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4355                 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4356
4357                 tried_agent = TRUE;
4358
4359                 logevent("Pageant is running. Requesting keys.");
4360
4361                 /* Request the keys held by the agent. */
4362                 PUT_32BIT(request, 1);
4363                 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4364                 agent_query(request, 5, &r, &responselen);
4365                 response = (unsigned char *) r;
4366                 if (response && responselen >= 5 &&
4367                     response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4368                     p = response + 5;
4369                     nkeys = GET_32BIT(p);
4370                     p += 4;
4371                     {
4372                         char buf[64];
4373                         sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4374                         logevent(buf);
4375                     }
4376                     for (i = 0; i < nkeys; i++) {
4377                         static char *pkblob, *alg, *commentp;
4378                         static int pklen, alglen, commentlen;
4379                         static int siglen, retlen, len;
4380                         static char *q, *agentreq, *ret;
4381                         void *vret;
4382
4383                         {
4384                             char buf[64];
4385                             sprintf(buf, "Trying Pageant key #%d", i);
4386                             logevent(buf);
4387                         }
4388                         pklen = GET_32BIT(p);
4389                         p += 4;
4390                         if (publickey_blob &&
4391                             pklen == publickey_bloblen &&
4392                             !memcmp(p, publickey_blob, publickey_bloblen)) {
4393                             logevent("This key matches configured key file");
4394                             tried_pubkey_config = 1;
4395                         }
4396                         pkblob = p;
4397                         p += pklen;
4398                         alglen = GET_32BIT(pkblob);
4399                         alg = pkblob + 4;
4400                         commentlen = GET_32BIT(p);
4401                         p += 4;
4402                         commentp = p;
4403                         p += commentlen;
4404                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4405                         ssh2_pkt_addstring(username);
4406                         ssh2_pkt_addstring("ssh-connection");   /* service requested */
4407                         ssh2_pkt_addstring("publickey");        /* method */
4408                         ssh2_pkt_addbool(FALSE);        /* no signature included */
4409                         ssh2_pkt_addstring_start();
4410                         ssh2_pkt_addstring_data(alg, alglen);
4411                         ssh2_pkt_addstring_start();
4412                         ssh2_pkt_addstring_data(pkblob, pklen);
4413                         ssh2_pkt_send();
4414
4415                         crWaitUntilV(ispkt);
4416                         if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4417                             logevent("Key refused");
4418                             continue;
4419                         }
4420
4421                         if (flags & FLAG_VERBOSE) {
4422                             c_write_str
4423                                 ("Authenticating with public key \"");
4424                             c_write(commentp, commentlen);
4425                             c_write_str("\" from agent\r\n");
4426                         }
4427
4428                         /*
4429                          * Server is willing to accept the key.
4430                          * Construct a SIGN_REQUEST.
4431                          */
4432                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4433                         ssh2_pkt_addstring(username);
4434                         ssh2_pkt_addstring("ssh-connection");   /* service requested */
4435                         ssh2_pkt_addstring("publickey");        /* method */
4436                         ssh2_pkt_addbool(TRUE);
4437                         ssh2_pkt_addstring_start();
4438                         ssh2_pkt_addstring_data(alg, alglen);
4439                         ssh2_pkt_addstring_start();
4440                         ssh2_pkt_addstring_data(pkblob, pklen);
4441
4442                         siglen = pktout.length - 5 + 4 + 20;
4443                         len = 1;       /* message type */
4444                         len += 4 + pklen;       /* key blob */
4445                         len += 4 + siglen;      /* data to sign */
4446                         len += 4;      /* flags */
4447                         agentreq = smalloc(4 + len);
4448                         PUT_32BIT(agentreq, len);
4449                         q = agentreq + 4;
4450                         *q++ = SSH2_AGENTC_SIGN_REQUEST;
4451                         PUT_32BIT(q, pklen);
4452                         q += 4;
4453                         memcpy(q, pkblob, pklen);
4454                         q += pklen;
4455                         PUT_32BIT(q, siglen);
4456                         q += 4;
4457                         /* Now the data to be signed... */
4458                         PUT_32BIT(q, 20);
4459                         q += 4;
4460                         memcpy(q, ssh2_session_id, 20);
4461                         q += 20;
4462                         memcpy(q, pktout.data + 5, pktout.length - 5);
4463                         q += pktout.length - 5;
4464                         /* And finally the (zero) flags word. */
4465                         PUT_32BIT(q, 0);
4466                         agent_query(agentreq, len + 4, &vret, &retlen);
4467                         ret = vret;
4468                         sfree(agentreq);
4469                         if (ret) {
4470                             if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4471                                 logevent("Sending Pageant's response");
4472                                 ssh2_add_sigblob(pkblob, pklen,
4473                                                  ret + 9, GET_32BIT(ret + 5));
4474                                 ssh2_pkt_send();
4475                                 authed = TRUE;
4476                                 break;
4477                             } else {
4478                                 logevent
4479                                     ("Pageant failed to answer challenge");
4480                                 sfree(ret);
4481                             }
4482                         }
4483                     }
4484                     if (authed)
4485                         continue;
4486                 }
4487             }
4488
4489             if (!method && can_pubkey && publickey_blob
4490                 && !tried_pubkey_config) {
4491                 unsigned char *pub_blob;
4492                 char *algorithm, *comment;
4493                 int pub_blob_len;
4494
4495                 tried_pubkey_config = TRUE;
4496
4497                 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4498                 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4499
4500                 /*
4501                  * Try the public key supplied in the configuration.
4502                  *
4503                  * First, offer the public blob to see if the server is
4504                  * willing to accept it.
4505                  */
4506                 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4507                                                 &pub_blob_len);
4508                 if (pub_blob) {
4509                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4510                     ssh2_pkt_addstring(username);
4511                     ssh2_pkt_addstring("ssh-connection");       /* service requested */
4512                     ssh2_pkt_addstring("publickey");    /* method */
4513                     ssh2_pkt_addbool(FALSE);    /* no signature included */
4514                     ssh2_pkt_addstring(algorithm);
4515                     ssh2_pkt_addstring_start();
4516                     ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4517                     ssh2_pkt_send();
4518                     logevent("Offered public key");     /* FIXME */
4519
4520                     crWaitUntilV(ispkt);
4521                     if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4522                         gotit = TRUE;
4523                         type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4524                         continue;      /* key refused; give up on it */
4525                     }
4526
4527                     logevent("Offer of public key accepted");
4528                     /*
4529                      * Actually attempt a serious authentication using
4530                      * the key.
4531                      */
4532                     if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4533                         sprintf(pwprompt,
4534                                 "Passphrase for key \"%.100s\": ",
4535                                 comment);
4536                         need_pw = TRUE;
4537                     } else {
4538                         need_pw = FALSE;
4539                     }
4540                     c_write_str("Authenticating with public key \"");
4541                     c_write_str(comment);
4542                     c_write_str("\"\r\n");
4543                     method = AUTH_PUBLICKEY_FILE;
4544                 }
4545             }
4546
4547             if (!method && can_keyb_inter && !tried_keyb_inter) {
4548                 method = AUTH_KEYBOARD_INTERACTIVE;
4549                 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4550                 tried_keyb_inter = TRUE;
4551
4552                 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4553                 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4554
4555                 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4556                 ssh2_pkt_addstring(username);
4557                 ssh2_pkt_addstring("ssh-connection");   /* service requested */
4558                 ssh2_pkt_addstring("keyboard-interactive");     /* method */
4559                 ssh2_pkt_addstring(""); /* lang */
4560                 ssh2_pkt_addstring("");
4561                 ssh2_pkt_send();
4562
4563                 crWaitUntilV(ispkt);
4564                 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4565                     if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4566                         gotit = TRUE;
4567                     logevent("Keyboard-interactive authentication refused");
4568                     type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4569                     continue;
4570                 }
4571
4572                 kbd_inter_running = TRUE;
4573                 curr_prompt = 0;
4574             }
4575
4576             if (kbd_inter_running) {
4577                 method = AUTH_KEYBOARD_INTERACTIVE;
4578                 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4579                 tried_keyb_inter = TRUE;
4580
4581                 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4582                 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4583
4584                 if (curr_prompt == 0) {
4585                     /*
4586                      * We've got a fresh USERAUTH_INFO_REQUEST.
4587                      * Display header data, and start going through
4588                      * the prompts.
4589                      */
4590                     char *name, *inst, *lang;
4591                     int name_len, inst_len, lang_len;
4592
4593                     ssh2_pkt_getstring(&name, &name_len);
4594                     ssh2_pkt_getstring(&inst, &inst_len);
4595                     ssh2_pkt_getstring(&lang, &lang_len);
4596                     if (name_len > 0) {
4597                         c_write_untrusted(name, name_len);
4598                         c_write_str("\r\n");
4599                     }
4600                     if (inst_len > 0) {
4601                         c_write_untrusted(inst, inst_len);
4602                         c_write_str("\r\n");
4603                     }
4604                     num_prompts = ssh2_pkt_getuint32();
4605                 }
4606
4607                 /*
4608                  * If there are prompts remaining in the packet,
4609                  * display one and get a response.
4610                  */
4611                 if (curr_prompt < num_prompts) {
4612                     char *prompt;
4613                     int prompt_len;
4614
4615                     ssh2_pkt_getstring(&prompt, &prompt_len);
4616                     if (prompt_len > 0) {
4617                         strncpy(pwprompt, prompt, sizeof(pwprompt));
4618                         pwprompt[prompt_len < sizeof(pwprompt) ?
4619                                  prompt_len : sizeof(pwprompt)-1] = '\0';
4620                     } else {
4621                         strcpy(pwprompt,
4622                                "<server failed to send prompt>: ");
4623                     }
4624                     echo = ssh2_pkt_getbool();
4625                     need_pw = TRUE;
4626                 } else
4627                     need_pw = FALSE;
4628             }
4629
4630             if (!method && can_passwd) {
4631                 method = AUTH_PASSWORD;
4632                 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4633                 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4634                 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4635                         savedhost);
4636                 need_pw = TRUE;
4637             }
4638
4639             if (need_pw) {
4640                 if (ssh_get_line) {
4641                     if (!ssh_get_line(pwprompt, password,
4642                                       sizeof(password), TRUE)) {
4643                         /*
4644                          * get_line failed to get a password (for
4645                          * example because one was supplied on the
4646                          * command line which has already failed to
4647                          * work). Terminate.
4648                          */
4649                         ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4650                         ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4651                         ssh2_pkt_addstring
4652                             ("No more passwords available to try");
4653                         ssh2_pkt_addstring("en");       /* language tag */
4654                         ssh2_pkt_send();
4655                         logevent("Unable to authenticate");
4656                         connection_fatal("Unable to authenticate");
4657                         ssh_state = SSH_STATE_CLOSED;
4658                         crReturnV;
4659                     }
4660                 } else {
4661                     static int ret;
4662                     c_write_untrusted(pwprompt, strlen(pwprompt));
4663                     ssh_send_ok = 1;
4664
4665                     setup_userpass_input(password, sizeof(password), echo);
4666                     do {
4667                         crWaitUntilV(!ispkt);
4668                         ret = process_userpass_input(in, inlen);
4669                     } while (ret == 0);
4670                     if (ret < 0)
4671                         cleanup_exit(0);
4672                     c_write_str("\r\n");
4673                 }
4674             }
4675
4676             if (method == AUTH_PUBLICKEY_FILE) {
4677                 /*
4678                  * We have our passphrase. Now try the actual authentication.
4679                  */
4680                 struct ssh2_userkey *key;
4681
4682                 key = ssh2_load_userkey(cfg.keyfile, password);
4683                 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4684                     if (key == SSH2_WRONG_PASSPHRASE) {
4685                         c_write_str("Wrong passphrase\r\n");
4686                         tried_pubkey_config = FALSE;
4687                     } else {
4688                         c_write_str("Unable to load private key\r\n");
4689                         tried_pubkey_config = TRUE;
4690                     }
4691                     /* Send a spurious AUTH_NONE to return to the top. */
4692                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4693                     ssh2_pkt_addstring(username);
4694                     ssh2_pkt_addstring("ssh-connection");       /* service requested */
4695                     ssh2_pkt_addstring("none"); /* method */
4696                     ssh2_pkt_send();
4697                     type = AUTH_TYPE_NONE;
4698                 } else {
4699                     unsigned char *pkblob, *sigblob, *sigdata;
4700                     int pkblob_len, sigblob_len, sigdata_len;
4701
4702                     /*
4703                      * We have loaded the private key and the server
4704                      * has announced that it's willing to accept it.
4705                      * Hallelujah. Generate a signature and send it.
4706                      */
4707                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4708                     ssh2_pkt_addstring(username);
4709                     ssh2_pkt_addstring("ssh-connection");       /* service requested */
4710                     ssh2_pkt_addstring("publickey");    /* method */
4711                     ssh2_pkt_addbool(TRUE);
4712                     ssh2_pkt_addstring(key->alg->name);
4713                     pkblob = key->alg->public_blob(key->data, &pkblob_len);
4714                     ssh2_pkt_addstring_start();
4715                     ssh2_pkt_addstring_data(pkblob, pkblob_len);
4716
4717                     /*
4718                      * The data to be signed is:
4719                      *
4720                      *   string  session-id
4721                      *
4722                      * followed by everything so far placed in the
4723                      * outgoing packet.
4724                      */
4725                     sigdata_len = pktout.length - 5 + 4 + 20;
4726                     sigdata = smalloc(sigdata_len);
4727                     PUT_32BIT(sigdata, 20);
4728                     memcpy(sigdata + 4, ssh2_session_id, 20);
4729                     memcpy(sigdata + 24, pktout.data + 5,
4730                            pktout.length - 5);
4731                     sigblob = key->alg->sign(key->data, sigdata,
4732                                              sigdata_len, &sigblob_len);
4733                     ssh2_add_sigblob(pkblob, pkblob_len,
4734                                      sigblob, sigblob_len);
4735                     sfree(pkblob);
4736                     sfree(sigblob);
4737                     sfree(sigdata);
4738
4739                     ssh2_pkt_send();
4740                     type = AUTH_TYPE_PUBLICKEY;
4741                 }
4742             } else if (method == AUTH_PASSWORD) {
4743                 /*
4744                  * We send the password packet lumped tightly together with
4745                  * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4746                  * string long enough to make the total length of the two
4747                  * packets constant. This should ensure that a passive
4748                  * listener doing traffic analyis can't work out the length
4749                  * of the password.
4750                  *
4751                  * For this to work, we need an assumption about the
4752                  * maximum length of the password packet. I think 256 is
4753                  * pretty conservative. Anyone using a password longer than
4754                  * that probably doesn't have much to worry about from
4755                  * people who find out how long their password is!
4756                  */
4757                 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4758                 ssh2_pkt_addstring(username);
4759                 ssh2_pkt_addstring("ssh-connection");   /* service requested */
4760                 ssh2_pkt_addstring("password");
4761                 ssh2_pkt_addbool(FALSE);
4762                 ssh2_pkt_addstring(password);
4763                 ssh2_pkt_defer();
4764                 /*
4765                  * We'll include a string that's an exact multiple of the
4766                  * cipher block size. If the cipher is NULL for some
4767                  * reason, we don't do this trick at all because we gain
4768                  * nothing by it.
4769                  */
4770                 if (cscipher) {
4771                     int stringlen, i;
4772
4773                     stringlen = (256 - deferred_len);
4774                     stringlen += cscipher->blksize - 1;
4775                     stringlen -= (stringlen % cscipher->blksize);
4776                     if (cscomp) {
4777                         /*
4778                          * Temporarily disable actual compression,
4779                          * so we can guarantee to get this string
4780                          * exactly the length we want it. The
4781                          * compression-disabling routine should
4782                          * return an integer indicating how many
4783                          * bytes we should adjust our string length
4784                          * by.
4785                          */
4786                         stringlen -= cscomp->disable_compression();
4787                     }
4788                     ssh2_pkt_init(SSH2_MSG_IGNORE);
4789                     ssh2_pkt_addstring_start();
4790                     for (i = 0; i < stringlen; i++) {
4791                         char c = (char) random_byte();
4792                         ssh2_pkt_addstring_data(&c, 1);
4793                     }
4794                     ssh2_pkt_defer();
4795                 }
4796                 ssh_pkt_defersend();
4797                 logevent("Sent password");
4798                 type = AUTH_TYPE_PASSWORD;
4799             } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4800                 if (curr_prompt == 0) {
4801                     ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4802                     ssh2_pkt_adduint32(num_prompts);
4803                 }
4804                 if (need_pw) {         /* only add pw if we just got one! */
4805                     ssh2_pkt_addstring(password);
4806                     memset(password, 0, sizeof(password));
4807                     curr_prompt++;
4808                 }
4809                 if (curr_prompt >= num_prompts) {
4810                     ssh2_pkt_send();
4811                 } else {
4812                     /*
4813                      * If there are prompts remaining, we set
4814                      * `gotit' so that we won't attempt to get
4815                      * another packet. Then we go back round the
4816                      * loop and will end up retrieving another
4817                      * prompt out of the existing packet. Funky or
4818                      * what?
4819                      */
4820                     gotit = TRUE;
4821                 }
4822                 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4823             } else {
4824                 c_write_str
4825                     ("No supported authentication methods left to try!\r\n");
4826                 logevent
4827                     ("No supported authentications offered. Disconnecting");
4828                 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4829                 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4830                 ssh2_pkt_addstring
4831                     ("No supported authentication methods available");
4832                 ssh2_pkt_addstring("en");       /* language tag */
4833                 ssh2_pkt_send();
4834                 ssh_state = SSH_STATE_CLOSED;
4835                 crReturnV;
4836             }
4837         }
4838     } while (!we_are_in);
4839
4840     /*
4841      * Now we're authenticated for the connection protocol. The
4842      * connection protocol will automatically have started at this
4843      * point; there's no need to send SERVICE_REQUEST.
4844      */
4845
4846     /*
4847      * So now create a channel with a session in it.
4848      */
4849     ssh_channels = newtree234(ssh_channelcmp);
4850     mainchan = smalloc(sizeof(struct ssh_channel));
4851     mainchan->localid = alloc_channel_id();
4852     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4853     ssh2_pkt_addstring("session");
4854     ssh2_pkt_adduint32(mainchan->localid);
4855     mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4856     ssh2_pkt_adduint32(mainchan->v.v2.locwindow);      /* our window size */
4857     ssh2_pkt_adduint32(0x4000UL);      /* our max pkt size */
4858     ssh2_pkt_send();
4859     crWaitUntilV(ispkt);
4860     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4861         bombout(("Server refused to open a session"));
4862         crReturnV;
4863         /* FIXME: error data comes back in FAILURE packet */
4864     }
4865     if (ssh2_pkt_getuint32() != mainchan->localid) {
4866         bombout(("Server's channel confirmation cited wrong channel"));
4867         crReturnV;
4868     }
4869     mainchan->remoteid = ssh2_pkt_getuint32();
4870     mainchan->type = CHAN_MAINSESSION;
4871     mainchan->closes = 0;
4872     mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4873     mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4874     bufchain_init(&mainchan->v.v2.outbuffer);
4875     add234(ssh_channels, mainchan);
4876     logevent("Opened channel for session");
4877
4878     /*
4879      * Potentially enable X11 forwarding.
4880      */
4881     if (cfg.x11_forward) {
4882         char proto[20], data[64];
4883         logevent("Requesting X11 forwarding");
4884         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4885         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4886         ssh2_pkt_adduint32(mainchan->remoteid);
4887         ssh2_pkt_addstring("x11-req");
4888         ssh2_pkt_addbool(1);           /* want reply */
4889         ssh2_pkt_addbool(0);           /* many connections */
4890         ssh2_pkt_addstring(proto);
4891         ssh2_pkt_addstring(data);
4892         ssh2_pkt_adduint32(0);         /* screen number */
4893         ssh2_pkt_send();
4894
4895         do {
4896             crWaitUntilV(ispkt);
4897             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4898                 unsigned i = ssh2_pkt_getuint32();
4899                 struct ssh_channel *c;
4900                 c = find234(ssh_channels, &i, ssh_channelfind);
4901                 if (!c)
4902                     continue;          /* nonexistent channel */
4903                 c->v.v2.remwindow += ssh2_pkt_getuint32();
4904             }
4905         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4906
4907         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4908             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4909                 bombout(("Unexpected response to X11 forwarding request:"
4910                          " packet type %d", pktin.type));
4911                 crReturnV;
4912             }
4913             logevent("X11 forwarding refused");
4914         } else {
4915             logevent("X11 forwarding enabled");
4916             ssh_X11_fwd_enabled = TRUE;
4917         }
4918     }
4919
4920     /*
4921      * Enable port forwardings.
4922      */
4923     {
4924         static char *e;                /* preserve across crReturn */
4925         char type;
4926         int n;
4927         int sport,dport,sserv,dserv;
4928         char sports[256], dports[256], host[256];
4929         char buf[1024];
4930         struct servent *se;
4931
4932         ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4933         /* Add port forwardings. */
4934         e = cfg.portfwd;
4935         while (*e) {
4936             type = *e++;
4937             n = 0;
4938             while (*e && *e != '\t')
4939                 sports[n++] = *e++;
4940             sports[n] = 0;
4941             if (*e == '\t')
4942                 e++;
4943             n = 0;
4944             while (*e && *e != ':')
4945                 host[n++] = *e++;
4946             host[n] = 0;
4947             if (*e == ':')
4948                 e++;
4949             n = 0;
4950             while (*e)
4951                 dports[n++] = *e++;
4952             dports[n] = 0;
4953             e++;
4954             dport = atoi(dports);
4955             dserv = 0;
4956             if (dport == 0) {
4957                 dserv = 1;
4958                 se = getservbyname(dports, NULL);
4959                 if (se != NULL) {
4960                     dport = ntohs(se->s_port);
4961                 } else {
4962                     sprintf(buf,
4963                             "Service lookup failed for destination port \"%s\"",
4964                             dports);
4965                     logevent(buf);
4966                 }
4967             }
4968             sport = atoi(sports);
4969             sserv = 0;
4970             if (sport == 0) {
4971                 sserv = 1;
4972                 se = getservbyname(sports, NULL);
4973                 if (se != NULL) {
4974                     sport = ntohs(se->s_port);
4975                 } else {
4976                     sprintf(buf,
4977                             "Service lookup failed for source port \"%s\"",
4978                             sports);
4979                     logevent(buf);
4980                 }
4981             }
4982             if (sport && dport) {
4983                 if (type == 'L') {
4984                     pfd_addforward(host, dport, sport);
4985                     sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
4986                             " %s:%.*s%.*s%d%.*s",
4987                             sserv ? strlen(sports) : 0, sports,
4988                             sserv, "(", sport, sserv, ")",
4989                             host,
4990                             dserv ? strlen(dports) : 0, dports,
4991                             dserv, "(", dport, dserv, ")");
4992                     logevent(buf);
4993                 } else {
4994                     struct ssh_rportfwd *pf;
4995                     pf = smalloc(sizeof(*pf));
4996                     strcpy(pf->dhost, host);
4997                     pf->dport = dport;
4998                     pf->sport = sport;
4999                     if (add234(ssh_rportfwds, pf) != pf) {
5000                         sprintf(buf, 
5001                                 "Duplicate remote port forwarding to %s:%d",
5002                                 host, dport);
5003                         logevent(buf);
5004                         sfree(pf);
5005                     } else {
5006                         sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5007                                 " forward to %s:%.*s%.*s%d%.*s",
5008                             sserv ? strlen(sports) : 0, sports,
5009                             sserv, "(", sport, sserv, ")",
5010                             host,
5011                             dserv ? strlen(dports) : 0, dports,
5012                             dserv, "(", dport, dserv, ")");
5013                         logevent(buf);
5014                         ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5015                         ssh2_pkt_addstring("tcpip-forward");
5016                         ssh2_pkt_addbool(1);/* want reply */
5017                         if (cfg.rport_acceptall)
5018                             ssh2_pkt_addstring("0.0.0.0");
5019                         else
5020                             ssh2_pkt_addstring("127.0.0.1");
5021                         ssh2_pkt_adduint32(sport);
5022                         ssh2_pkt_send();
5023
5024                         do {
5025                             crWaitUntilV(ispkt);
5026                             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5027                                 unsigned i = ssh2_pkt_getuint32();
5028                                 struct ssh_channel *c;
5029                                 c = find234(ssh_channels, &i, ssh_channelfind);
5030                                 if (!c)
5031                                     continue;/* nonexistent channel */
5032                                 c->v.v2.remwindow += ssh2_pkt_getuint32();
5033                             }
5034                         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5035
5036                         if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5037                             if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5038                                 bombout(("Unexpected response to port "
5039                                          "forwarding request: packet type %d",
5040                                          pktin.type));
5041                                 crReturnV;
5042                             }
5043                             logevent("Server refused this port forwarding");
5044                         } else {
5045                             logevent("Remote port forwarding enabled");
5046                         }
5047                     }
5048                 }
5049             }
5050         }
5051     }
5052
5053     /*
5054      * Potentially enable agent forwarding.
5055      */
5056     if (cfg.agentfwd && agent_exists()) {
5057         logevent("Requesting OpenSSH-style agent forwarding");
5058         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5059         ssh2_pkt_adduint32(mainchan->remoteid);
5060         ssh2_pkt_addstring("auth-agent-req@openssh.com");
5061         ssh2_pkt_addbool(1);           /* want reply */
5062         ssh2_pkt_send();
5063
5064         do {
5065             crWaitUntilV(ispkt);
5066             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5067                 unsigned i = ssh2_pkt_getuint32();
5068                 struct ssh_channel *c;
5069                 c = find234(ssh_channels, &i, ssh_channelfind);
5070                 if (!c)
5071                     continue;          /* nonexistent channel */
5072                 c->v.v2.remwindow += ssh2_pkt_getuint32();
5073             }
5074         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5075
5076         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5077             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5078                 bombout(("Unexpected response to agent forwarding request:"
5079                          " packet type %d", pktin.type));
5080                 crReturnV;
5081             }
5082             logevent("Agent forwarding refused");
5083         } else {
5084             logevent("Agent forwarding enabled");
5085             ssh_agentfwd_enabled = TRUE;
5086         }
5087     }
5088
5089     /*
5090      * Now allocate a pty for the session.
5091      */
5092     if (!cfg.nopty) {
5093         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5094         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5095         ssh2_pkt_addstring("pty-req");
5096         ssh2_pkt_addbool(1);           /* want reply */
5097         ssh2_pkt_addstring(cfg.termtype);
5098         ssh2_pkt_adduint32(cols);
5099         ssh2_pkt_adduint32(rows);
5100         ssh2_pkt_adduint32(0);         /* pixel width */
5101         ssh2_pkt_adduint32(0);         /* pixel height */
5102         ssh2_pkt_addstring_start();
5103         ssh2_pkt_addstring_data("\0", 1);       /* TTY_OP_END, no special options */
5104         ssh2_pkt_send();
5105         ssh_state = SSH_STATE_INTERMED;
5106
5107         do {
5108             crWaitUntilV(ispkt);
5109             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5110                 unsigned i = ssh2_pkt_getuint32();
5111                 struct ssh_channel *c;
5112                 c = find234(ssh_channels, &i, ssh_channelfind);
5113                 if (!c)
5114                     continue;          /* nonexistent channel */
5115                 c->v.v2.remwindow += ssh2_pkt_getuint32();
5116             }
5117         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5118
5119         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5120             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5121                 bombout(("Unexpected response to pty request:"
5122                          " packet type %d", pktin.type));
5123                 crReturnV;
5124             }
5125             c_write_str("Server refused to allocate pty\r\n");
5126             ssh_editing = ssh_echoing = 1;
5127         } else {
5128             logevent("Allocated pty");
5129         }
5130     } else {
5131         ssh_editing = ssh_echoing = 1;
5132     }
5133
5134     /*
5135      * Start a shell or a remote command. We may have to attempt
5136      * this twice if the config data has provided a second choice
5137      * of command.
5138      */
5139     while (1) {
5140         int subsys;
5141         char *cmd;
5142
5143         if (ssh_fallback_cmd) {
5144             subsys = cfg.ssh_subsys2;
5145             cmd = cfg.remote_cmd_ptr2;
5146         } else {
5147             subsys = cfg.ssh_subsys;
5148             cmd = cfg.remote_cmd_ptr;
5149         }
5150
5151         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5152         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5153         if (subsys) {
5154             ssh2_pkt_addstring("subsystem");
5155             ssh2_pkt_addbool(1);               /* want reply */
5156             ssh2_pkt_addstring(cmd);
5157         } else if (*cmd) {
5158             ssh2_pkt_addstring("exec");
5159             ssh2_pkt_addbool(1);               /* want reply */
5160             ssh2_pkt_addstring(cmd);
5161         } else {
5162             ssh2_pkt_addstring("shell");
5163             ssh2_pkt_addbool(1);               /* want reply */
5164         }
5165         ssh2_pkt_send();
5166         do {
5167             crWaitUntilV(ispkt);
5168             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5169                 unsigned i = ssh2_pkt_getuint32();
5170                 struct ssh_channel *c;
5171                 c = find234(ssh_channels, &i, ssh_channelfind);
5172                 if (!c)
5173                     continue;          /* nonexistent channel */
5174                 c->v.v2.remwindow += ssh2_pkt_getuint32();
5175             }
5176         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5177         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5178             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5179                 bombout(("Unexpected response to shell/command request:"
5180                          " packet type %d", pktin.type));
5181                 crReturnV;
5182             }
5183             /*
5184              * We failed to start the command. If this is the
5185              * fallback command, we really are finished; if it's
5186              * not, and if the fallback command exists, try falling
5187              * back to it before complaining.
5188              */
5189             if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5190                 logevent("Primary command failed; attempting fallback");
5191                 ssh_fallback_cmd = TRUE;
5192                 continue;
5193             }
5194             bombout(("Server refused to start a shell/command"));
5195             crReturnV;
5196         } else {
5197             logevent("Started a shell/command");
5198         }
5199         break;
5200     }
5201
5202     ssh_state = SSH_STATE_SESSION;
5203     if (size_needed)
5204         ssh_size();
5205     if (eof_needed)
5206         ssh_special(TS_EOF);
5207
5208     /*
5209      * Transfer data!
5210      */
5211     ldisc_send(NULL, 0, 0);            /* cause ldisc to notice changes */
5212     ssh_send_ok = 1;
5213     while (1) {
5214         static int try_send;
5215         crReturnV;
5216         try_send = FALSE;
5217         if (ispkt) {
5218             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
5219                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5220                 char *data;
5221                 int length;
5222                 unsigned i = ssh2_pkt_getuint32();
5223                 struct ssh_channel *c;
5224                 c = find234(ssh_channels, &i, ssh_channelfind);
5225                 if (!c)
5226                     continue;          /* nonexistent channel */
5227                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5228                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
5229                     continue;          /* extended but not stderr */
5230                 ssh2_pkt_getstring(&data, &length);
5231                 if (data) {
5232                     int bufsize;
5233                     c->v.v2.locwindow -= length;
5234                     switch (c->type) {
5235                       case CHAN_MAINSESSION:
5236                         bufsize =
5237                             from_backend(pktin.type ==
5238                                          SSH2_MSG_CHANNEL_EXTENDED_DATA,
5239                                          data, length);
5240                         break;
5241                       case CHAN_X11:
5242                         bufsize = x11_send(c->u.x11.s, data, length);
5243                         break;
5244                       case CHAN_SOCKDATA:
5245                         bufsize = pfd_send(c->u.pfd.s, data, length);
5246                         break;
5247                       case CHAN_AGENT:
5248                         while (length > 0) {
5249                             if (c->u.a.lensofar < 4) {
5250                                 int l = min(4 - c->u.a.lensofar, length);
5251                                 memcpy(c->u.a.msglen + c->u.a.lensofar,
5252                                        data, l);
5253                                 data += l;
5254                                 length -= l;
5255                                 c->u.a.lensofar += l;
5256                             }
5257                             if (c->u.a.lensofar == 4) {
5258                                 c->u.a.totallen =
5259                                     4 + GET_32BIT(c->u.a.msglen);
5260                                 c->u.a.message = smalloc(c->u.a.totallen);
5261                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
5262                             }
5263                             if (c->u.a.lensofar >= 4 && length > 0) {
5264                                 int l =
5265                                     min(c->u.a.totallen - c->u.a.lensofar,
5266                                         length);
5267                                 memcpy(c->u.a.message + c->u.a.lensofar,
5268                                        data, l);
5269                                 data += l;
5270                                 length -= l;
5271                                 c->u.a.lensofar += l;
5272                             }
5273                             if (c->u.a.lensofar == c->u.a.totallen) {
5274                                 void *reply, *sentreply;
5275                                 int replylen;
5276                                 agent_query(c->u.a.message,
5277                                             c->u.a.totallen, &reply,
5278                                             &replylen);
5279                                 if (reply)
5280                                     sentreply = reply;
5281                                 else {
5282                                     /* Fake SSH_AGENT_FAILURE. */
5283                                     sentreply = "\0\0\0\1\5";
5284                                     replylen = 5;
5285                                 }
5286                                 ssh2_add_channel_data(c, sentreply,
5287                                                       replylen);
5288                                 try_send = TRUE;
5289                                 if (reply)
5290                                     sfree(reply);
5291                                 sfree(c->u.a.message);
5292                                 c->u.a.lensofar = 0;
5293                             }
5294                         }
5295                         bufsize = 0;
5296                         break;
5297                     }
5298                     /*
5299                      * If we are not buffering too much data,
5300                      * enlarge the window again at the remote side.
5301                      */
5302                     if (bufsize < OUR_V2_WINSIZE)
5303                         ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5304                 }
5305             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5306                 ssh_state = SSH_STATE_CLOSED;
5307                 logevent("Received disconnect message");
5308                 crReturnV;
5309             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5310                 unsigned i = ssh2_pkt_getuint32();
5311                 struct ssh_channel *c;
5312
5313                 c = find234(ssh_channels, &i, ssh_channelfind);
5314                 if (!c)
5315                     continue;          /* nonexistent channel */
5316
5317                 if (c->type == CHAN_X11) {
5318                     /*
5319                      * Remote EOF on an X11 channel means we should
5320                      * wrap up and close the channel ourselves.
5321                      */
5322                     x11_close(c->u.x11.s);
5323                     sshfwd_close(c);
5324                 } else if (c->type == CHAN_AGENT) {
5325                     sshfwd_close(c);
5326                 } else if (c->type == CHAN_SOCKDATA) {
5327                     pfd_close(c->u.pfd.s);
5328                     sshfwd_close(c);
5329                 }
5330             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5331                 unsigned i = ssh2_pkt_getuint32();
5332                 struct ssh_channel *c;
5333
5334                 c = find234(ssh_channels, &i, ssh_channelfind);
5335                 if (!c)
5336                     continue;          /* nonexistent channel */
5337                 /* Do pre-close processing on the channel. */
5338                 switch (c->type) {
5339                   case CHAN_MAINSESSION:
5340                     break;             /* nothing to see here, move along */
5341                   case CHAN_X11:
5342                     if (c->u.x11.s != NULL)
5343                         x11_close(c->u.x11.s);
5344                     sshfwd_close(c);
5345                     break;
5346                   case CHAN_AGENT:
5347                     sshfwd_close(c);
5348                     break;
5349                   case CHAN_SOCKDATA:
5350                     if (c->u.pfd.s != NULL)
5351                         pfd_close(c->u.pfd.s);
5352                     sshfwd_close(c);
5353                     break;
5354                 }
5355                 if (c->closes == 0) {
5356                     ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5357                     ssh2_pkt_adduint32(c->remoteid);
5358                     ssh2_pkt_send();
5359                 }
5360                 del234(ssh_channels, c);
5361                 bufchain_clear(&c->v.v2.outbuffer);
5362                 sfree(c);
5363
5364                 /*
5365                  * See if that was the last channel left open.
5366                  */
5367                 if (count234(ssh_channels) == 0) {
5368 #if 0
5369                     /*
5370                      * We used to send SSH_MSG_DISCONNECT here,
5371                      * because I'd believed that _every_ conforming
5372                      * SSH2 connection had to end with a disconnect
5373                      * being sent by at least one side; apparently
5374                      * I was wrong and it's perfectly OK to
5375                      * unceremoniously slam the connection shut
5376                      * when you're done, and indeed OpenSSH feels
5377                      * this is more polite than sending a
5378                      * DISCONNECT. So now we don't.
5379                      */
5380                     logevent("All channels closed. Disconnecting");
5381                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5382                     ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5383                     ssh2_pkt_addstring("All open channels closed");
5384                     ssh2_pkt_addstring("en");   /* language tag */
5385                     ssh2_pkt_send();
5386 #endif
5387                     ssh_state = SSH_STATE_CLOSED;
5388                     crReturnV;
5389                 }
5390                 continue;              /* remote sends close; ignore (FIXME) */
5391             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5392                 unsigned i = ssh2_pkt_getuint32();
5393                 struct ssh_channel *c;
5394                 c = find234(ssh_channels, &i, ssh_channelfind);
5395                 if (!c)
5396                     continue;          /* nonexistent channel */
5397                 c->v.v2.remwindow += ssh2_pkt_getuint32();
5398                 try_send = TRUE;
5399             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5400                 unsigned i = ssh2_pkt_getuint32();
5401                 struct ssh_channel *c;
5402                 c = find234(ssh_channels, &i, ssh_channelfind);
5403                 if (!c)
5404                     continue;          /* nonexistent channel */
5405                 if (c->type != CHAN_SOCKDATA_DORMANT)
5406                     continue;          /* dunno why they're confirming this */
5407                 c->remoteid = ssh2_pkt_getuint32();
5408                 c->type = CHAN_SOCKDATA;
5409                 c->v.v2.remwindow = ssh2_pkt_getuint32();
5410                 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5411                 if (c->u.pfd.s)
5412                     pfd_confirm(c->u.pfd.s);
5413                 if (c->closes) {
5414                     /*
5415                      * We have a pending close on this channel,
5416                      * which we decided on before the server acked
5417                      * the channel open. So now we know the
5418                      * remoteid, we can close it again.
5419                      */
5420                     ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5421                     ssh2_pkt_adduint32(c->remoteid);
5422                     ssh2_pkt_send();
5423                 }
5424             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5425                 unsigned i = ssh2_pkt_getuint32();
5426                 struct ssh_channel *c;
5427                 c = find234(ssh_channels, &i, ssh_channelfind);
5428                 if (!c)
5429                     continue;          /* nonexistent channel */
5430                 if (c->type != CHAN_SOCKDATA_DORMANT)
5431                     continue;          /* dunno why they're failing this */
5432
5433                 logevent("Forwarded connection refused by server");
5434
5435                 pfd_close(c->u.pfd.s);
5436
5437                 del234(ssh_channels, c);
5438                 sfree(c);
5439             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5440                 unsigned localid;
5441                 char *type;
5442                 int typelen, want_reply;
5443                 struct ssh_channel *c;
5444
5445                 localid = ssh2_pkt_getuint32();
5446                 ssh2_pkt_getstring(&type, &typelen);
5447                 want_reply = ssh2_pkt_getbool();
5448
5449                 /*
5450                  * First, check that the channel exists. Otherwise,
5451                  * we can instantly disconnect with a rude message.
5452                  */
5453                 c = find234(ssh_channels, &localid, ssh_channelfind);
5454                 if (!c) {
5455                     char buf[80];
5456                     sprintf(buf, "Received channel request for nonexistent"
5457                             " channel %d", localid);
5458                     logevent(buf);
5459                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5460                     ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5461                     ssh2_pkt_addstring(buf);
5462                     ssh2_pkt_addstring("en");   /* language tag */
5463                     ssh2_pkt_send();
5464                     connection_fatal("%s", buf);
5465                     ssh_state = SSH_STATE_CLOSED;
5466                     crReturnV;
5467                 }
5468
5469                 /*
5470                  * Having got the channel number, we now look at
5471                  * the request type string to see if it's something
5472                  * we recognise.
5473                  */
5474                 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5475                     c == mainchan) {
5476                     /* We recognise "exit-status" on the primary channel. */
5477                     char buf[100];
5478                     ssh_exitcode = ssh2_pkt_getuint32();
5479                     sprintf(buf, "Server sent command exit status %d",
5480                             ssh_exitcode);
5481                     logevent(buf);
5482                     if (want_reply) {
5483                         ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5484                         ssh2_pkt_adduint32(c->remoteid);
5485                         ssh2_pkt_send();
5486                     }
5487                 } else {
5488                     /*
5489                      * This is a channel request we don't know
5490                      * about, so we now either ignore the request
5491                      * or respond with CHANNEL_FAILURE, depending
5492                      * on want_reply.
5493                      */
5494                     if (want_reply) {
5495                         ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5496                         ssh2_pkt_adduint32(c->remoteid);
5497                         ssh2_pkt_send();
5498                     }
5499                 }
5500             } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5501                 char *type;
5502                 int typelen, want_reply;
5503
5504                 ssh2_pkt_getstring(&type, &typelen);
5505                 want_reply = ssh2_pkt_getbool();
5506
5507                 /*
5508                  * We currently don't support any global requests
5509                  * at all, so we either ignore the request or
5510                  * respond with REQUEST_FAILURE, depending on
5511                  * want_reply.
5512                  */
5513                 if (want_reply) {
5514                     ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5515                     ssh2_pkt_send();
5516                 }
5517             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5518                 char *type;
5519                 int typelen;
5520                 char *error = NULL;
5521                 struct ssh_channel *c;
5522                 unsigned remid, winsize, pktsize;
5523                 ssh2_pkt_getstring(&type, &typelen);
5524                 c = smalloc(sizeof(struct ssh_channel));
5525
5526                 remid = ssh2_pkt_getuint32();
5527                 winsize = ssh2_pkt_getuint32();
5528                 pktsize = ssh2_pkt_getuint32();
5529
5530                 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5531                     if (!ssh_X11_fwd_enabled)
5532                         error = "X11 forwarding is not enabled";
5533                     else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5534                              NULL) {
5535                         error = "Unable to open an X11 connection";
5536                     } else {
5537                         c->type = CHAN_X11;
5538                     }
5539                 } else if (typelen == 15 &&
5540                            !memcmp(type, "forwarded-tcpip", 15)) {
5541                     struct ssh_rportfwd pf, *realpf;
5542                     char *dummy;
5543                     int dummylen;
5544                     ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5545                     pf.sport = ssh2_pkt_getuint32();
5546                     realpf = find234(ssh_rportfwds, &pf, NULL);
5547                     if (realpf == NULL) {
5548                         error = "Remote port is not recognised";
5549                     } else {
5550                         char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5551                                                  realpf->dport, c);
5552                         char buf[1024];
5553                         sprintf(buf, "Received remote port open request for %s:%d",
5554                                 realpf->dhost, realpf->dport);
5555                         logevent(buf);
5556                         if (e != NULL) {
5557                             sprintf(buf, "Port open failed: %s", e);
5558                             logevent(buf);
5559                             error = "Port open failed";
5560                         } else {
5561                             logevent("Forwarded port opened successfully");
5562                             c->type = CHAN_SOCKDATA;
5563                         }
5564                     }
5565                 } else if (typelen == 22 &&
5566                            !memcmp(type, "auth-agent@openssh.com", 3)) {
5567                     if (!ssh_agentfwd_enabled)
5568                         error = "Agent forwarding is not enabled";
5569                     else {
5570                         c->type = CHAN_AGENT;   /* identify channel type */
5571                         c->u.a.lensofar = 0;
5572                     }
5573                 } else {
5574                     error = "Unsupported channel type requested";
5575                 }
5576
5577                 c->remoteid = remid;
5578                 if (error) {
5579                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5580                     ssh2_pkt_adduint32(c->remoteid);
5581                     ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5582                     ssh2_pkt_addstring(error);
5583                     ssh2_pkt_addstring("en");   /* language tag */
5584                     ssh2_pkt_send();
5585                     sfree(c);
5586                 } else {
5587                     c->localid = alloc_channel_id();
5588                     c->closes = 0;
5589                     c->v.v2.locwindow = OUR_V2_WINSIZE;
5590                     c->v.v2.remwindow = winsize;
5591                     c->v.v2.remmaxpkt = pktsize;
5592                     bufchain_init(&c->v.v2.outbuffer);
5593                     add234(ssh_channels, c);
5594                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5595                     ssh2_pkt_adduint32(c->remoteid);
5596                     ssh2_pkt_adduint32(c->localid);
5597                     ssh2_pkt_adduint32(c->v.v2.locwindow);
5598                     ssh2_pkt_adduint32(0x4000UL);       /* our max pkt size */
5599                     ssh2_pkt_send();
5600                 }
5601             } else {
5602                 bombout(("Strange packet received: type %d", pktin.type));
5603                 crReturnV;
5604             }
5605         } else {
5606             /*
5607              * We have spare data. Add it to the channel buffer.
5608              */
5609             ssh2_add_channel_data(mainchan, in, inlen);
5610             try_send = TRUE;
5611         }
5612         if (try_send) {
5613             int i;
5614             struct ssh_channel *c;
5615             /*
5616              * Try to send data on all channels if we can.
5617              */
5618             for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5619                 int bufsize = ssh2_try_send(c);
5620                 if (bufsize == 0) {
5621                     switch (c->type) {
5622                       case CHAN_MAINSESSION:
5623                         /* stdin need not receive an unthrottle
5624                          * notification since it will be polled */
5625                         break;
5626                       case CHAN_X11:
5627                         x11_unthrottle(c->u.x11.s);
5628                         break;
5629                       case CHAN_AGENT:
5630                         /* agent sockets are request/response and need no
5631                          * buffer management */
5632                         break;
5633                       case CHAN_SOCKDATA:
5634                         pfd_unthrottle(c->u.pfd.s);
5635                         break;
5636                     }
5637                 }
5638             }
5639         }
5640     }
5641
5642     crFinishV;
5643 }
5644
5645 /*
5646  * Handle the top-level SSH2 protocol.
5647  */
5648 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5649 {
5650     if (do_ssh2_transport(in, inlen, ispkt) == 0)
5651         return;
5652     do_ssh2_authconn(in, inlen, ispkt);
5653 }
5654
5655 /*
5656  * Called to set up the connection.
5657  *
5658  * Returns an error message, or NULL on success.
5659  */
5660 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5661 {
5662     char *p;
5663
5664 #ifdef MSCRYPTOAPI
5665     if (crypto_startup() == 0)
5666         return "Microsoft high encryption pack not installed!";
5667 #endif
5668
5669     ssh_send_ok = 0;
5670     ssh_editing = 0;
5671     ssh_echoing = 0;
5672     ssh1_throttle_count = 0;
5673     ssh_overall_bufsize = 0;
5674     ssh_fallback_cmd = 0;
5675
5676     p = connect_to_host(host, port, realhost, nodelay);
5677     if (p != NULL)
5678         return p;
5679
5680     return NULL;
5681 }
5682
5683 /*
5684  * Called to send data down the Telnet connection.
5685  */
5686 static int ssh_send(char *buf, int len)
5687 {
5688     if (s == NULL || ssh_protocol == NULL)
5689         return 0;
5690
5691     ssh_protocol(buf, len, 0);
5692
5693     return ssh_sendbuffer();
5694 }
5695
5696 /*
5697  * Called to query the current amount of buffered stdin data.
5698  */
5699 static int ssh_sendbuffer(void)
5700 {
5701     int override_value;
5702
5703     if (s == NULL || ssh_protocol == NULL)
5704         return 0;
5705
5706     /*
5707      * If the SSH socket itself has backed up, add the total backup
5708      * size on that to any individual buffer on the stdin channel.
5709      */
5710     override_value = 0;
5711     if (ssh_throttled_all)
5712         override_value = ssh_overall_bufsize;
5713
5714     if (ssh_version == 1) {
5715         return override_value;
5716     } else if (ssh_version == 2) {
5717         if (!mainchan || mainchan->closes > 0)
5718             return override_value;
5719         else
5720             return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5721     }
5722
5723     return 0;
5724 }
5725
5726 /*
5727  * Called to set the size of the window from SSH's POV.
5728  */
5729 static void ssh_size(void)
5730 {
5731     switch (ssh_state) {
5732       case SSH_STATE_BEFORE_SIZE:
5733       case SSH_STATE_PREPACKET:
5734       case SSH_STATE_CLOSED:
5735         break;                         /* do nothing */
5736       case SSH_STATE_INTERMED:
5737         size_needed = TRUE;            /* buffer for later */
5738         break;
5739       case SSH_STATE_SESSION:
5740         if (!cfg.nopty) {
5741             if (ssh_version == 1) {
5742                 send_packet(SSH1_CMSG_WINDOW_SIZE,
5743                             PKT_INT, rows, PKT_INT, cols,
5744                             PKT_INT, 0, PKT_INT, 0, PKT_END);
5745             } else {
5746                 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5747                 ssh2_pkt_adduint32(mainchan->remoteid);
5748                 ssh2_pkt_addstring("window-change");
5749                 ssh2_pkt_addbool(0);
5750                 ssh2_pkt_adduint32(cols);
5751                 ssh2_pkt_adduint32(rows);
5752                 ssh2_pkt_adduint32(0);
5753                 ssh2_pkt_adduint32(0);
5754                 ssh2_pkt_send();
5755             }
5756         }
5757         break;
5758     }
5759 }
5760
5761 /*
5762  * Send Telnet special codes. TS_EOF is useful for `plink', so you
5763  * can send an EOF and collect resulting output (e.g. `plink
5764  * hostname sort').
5765  */
5766 static void ssh_special(Telnet_Special code)
5767 {
5768     if (code == TS_EOF) {
5769         if (ssh_state != SSH_STATE_SESSION) {
5770             /*
5771              * Buffer the EOF in case we are pre-SESSION, so we can
5772              * send it as soon as we reach SESSION.
5773              */
5774             if (code == TS_EOF)
5775                 eof_needed = TRUE;
5776             return;
5777         }
5778         if (ssh_version == 1) {
5779             send_packet(SSH1_CMSG_EOF, PKT_END);
5780         } else {
5781             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5782             ssh2_pkt_adduint32(mainchan->remoteid);
5783             ssh2_pkt_send();
5784         }
5785         logevent("Sent EOF message");
5786     } else if (code == TS_PING) {
5787         if (ssh_state == SSH_STATE_CLOSED
5788             || ssh_state == SSH_STATE_PREPACKET) return;
5789         if (ssh_version == 1) {
5790             send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5791         } else {
5792             ssh2_pkt_init(SSH2_MSG_IGNORE);
5793             ssh2_pkt_addstring_start();
5794             ssh2_pkt_send();
5795         }
5796     } else {
5797         /* do nothing */
5798     }
5799 }
5800
5801 void *new_sock_channel(Socket s)
5802 {
5803     struct ssh_channel *c;
5804     c = smalloc(sizeof(struct ssh_channel));
5805
5806     if (c) {
5807         c->remoteid = -1;              /* to be set when open confirmed */
5808         c->localid = alloc_channel_id();
5809         c->closes = 0;
5810         c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5811         c->u.pfd.s = s;
5812         bufchain_init(&c->v.v2.outbuffer);
5813         add234(ssh_channels, c);
5814     }
5815     return c;
5816 }
5817
5818 /*
5819  * This is called when stdout/stderr (the entity to which
5820  * from_backend sends data) manages to clear some backlog.
5821  */
5822 void ssh_unthrottle(int bufsize)
5823 {
5824     if (ssh_version == 1) {
5825         if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5826             ssh1_stdout_throttling = 0;
5827             ssh1_throttle(-1);
5828         }
5829     } else {
5830         if (mainchan && mainchan->closes == 0)
5831             ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5832     }
5833 }
5834
5835 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5836 {
5837     struct ssh_channel *c = (struct ssh_channel *)channel;
5838     char buf[1024];
5839
5840     sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5841     logevent(buf);
5842
5843     if (ssh_version == 1) {
5844         send_packet(SSH1_MSG_PORT_OPEN,
5845                     PKT_INT, c->localid,
5846                     PKT_STR, hostname,
5847                     PKT_INT, port,
5848                     //PKT_STR, <org:orgport>,
5849                     PKT_END);
5850     } else {
5851         ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5852         ssh2_pkt_addstring("direct-tcpip");
5853         ssh2_pkt_adduint32(c->localid);
5854         c->v.v2.locwindow = OUR_V2_WINSIZE;
5855         ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5856         ssh2_pkt_adduint32(0x4000UL);      /* our max pkt size */
5857         ssh2_pkt_addstring(hostname);
5858         ssh2_pkt_adduint32(port);
5859         /*
5860          * We make up values for the originator data; partly it's
5861          * too much hassle to keep track, and partly I'm not
5862          * convinced the server should be told details like that
5863          * about my local network configuration.
5864          */
5865         ssh2_pkt_addstring("client-side-connection");
5866         ssh2_pkt_adduint32(0);
5867         ssh2_pkt_send();
5868     }
5869 }
5870
5871
5872 static Socket ssh_socket(void)
5873 {
5874     return s;
5875 }
5876
5877 static int ssh_sendok(void)
5878 {
5879     return ssh_send_ok;
5880 }
5881
5882 static int ssh_ldisc(int option)
5883 {
5884     if (option == LD_ECHO)
5885         return ssh_echoing;
5886     if (option == LD_EDIT)
5887         return ssh_editing;
5888     return FALSE;
5889 }
5890
5891 static int ssh_return_exitcode(void)
5892 {
5893     return ssh_exitcode;
5894 }
5895
5896 Backend ssh_backend = {
5897     ssh_init,
5898     ssh_send,
5899     ssh_sendbuffer,
5900     ssh_size,
5901     ssh_special,
5902     ssh_socket,
5903     ssh_return_exitcode,
5904     ssh_sendok,
5905     ssh_ldisc,
5906     ssh_unthrottle,
5907     22
5908 };