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