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