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