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