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